Merge Lists in Python

Python Program to Merge Lists Using Naive Method

# Python Program to Merge Lists Using Naive Method
 
# Initializing lists
list1 = [1, 6, 3, 5, 2, 9]
list2 = [3, 5, 7, 8, 5]
 
# using naive method to merge list
for i in list2 :
    list1.append(i)
 
# Printing merged list
print ("Merged list using naive method : \n"+ str(list1))

Output:

Merged list using naive method : 
[1, 6, 3, 5, 2, 9, 3, 5, 7, 8, 5]

Python Program to Merge Lists Using + operator

# Python Program to Merge Lists Using + operator

# Initializing lists
li3 = [6, 4, 3, 6, 5]
li4 = [5, 8, 6, 4, 9]

# using + operator to merge
li3 = li3 + li4

# Printing Merged list
print ("Merged list using + : \n"+ str(li3))

Output:

Merged list using + : 
[6, 4, 3, 6, 5, 5, 8, 6, 4, 9]

Python Program to Merge Lists Using Comprehension

# Python Program to Merge Lists Using Comprehension 

# Initializing lists
l1 = [5, 1, 4, 6, 2]
l2 = [6, 9, 7, 2, 5, 6]

# using list comprehension to merge
res_list = [y for x in [l1, l2] for y in x]

# Printing merged list
print ("Merged list using list comprehension: \n" + str(res_list))

Output:

Merged list using list comprehension: 
[5, 1, 4, 6, 2, 6, 9, 7, 2, 5, 6]

Python Program to Merge List Using extend()

# Python Program to Merge Lists Using extend()

# Initializing lists
test_l3 = [1, 4, 5, 6, 5]
test_l4 = [3, 5, 7, 2, 5]

# using list.extend() to merge
test_l3.extend(test_l4)

# Printing merged list
print ("merged list using list.extend() : \n"+ str(test_l3))

Output:

merged list using list.extend() : 
[1, 4, 5, 6, 5, 3, 5, 7, 2, 5]

About The Author

Leave a Reply