How to append list to second list (concatenate lists) in Python?

PythonServer Side ProgrammingProgramming

This can be done in different ways −

Using concatenation operator

Example

l1=[1,2,3]
l2=[2,3,4]
l3=l1+l2
print ('new list', l3)

Output

This will print

new list [1, 2, 3, 2, 3, 4]

Using append method of list object

Example

l1=[1,2,3]
l1=[3,4,5]
l1.append(l2)
print ('appended list', l1)

Output

Here’s the result

appended list [3, 4, 5, [2, 3, 4]]

Using extend method

Example

l1=[1,2,3]
l1=[3,4,5]
l1.extend(l2)
print ('extended list', l1)

Output

The output is as follows −

extended list [1, 2, 3, 3, 4, 5]

Obtain list without duplicates

First concatenate list, then use set() function to eliminate duplicates and then use list() function to convert set to list

Example

l1=[1,2,3]
l2=[3,4,5]
l=list(set(l1+l2))
print ('list without duplicates',l)

Output

Resulting list object will be

list without duplicates [1, 2, 3, 4, 5]


raja
Published on 12-Jan-2018 19:17:53
Advertisements