, asked
Views : 10

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

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

1 Answer
Malhar Lathkar

This can be done in different ways:

Using concatenation operator

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

This will print

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

Using append method of list object

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

Here’s the result

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

Using extend method

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

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

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

Resulting list object will be

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

Advertisements
Related Questions