join lists in python with different methods

In this example, you will define two lists with different values and join or merge them.

You can join two or more list using various methods. Most common and easiest way is join them with + operator.

Example 1 : Join using + operator

    
# python program to join two lists using + operator

lst1 = [1,2,3,4]
lst2 = [5,6,7,8]

joined = lst1 + lst2

print(joined)
       

Output :

    
[1, 2, 3, 4, 5, 6, 7, 8]
    

Another way to join two lists are by appending all the items of secondary loop to primary loop one by one.

Example 2 : Join using Append

    
# Merge lists using append in python

lst1 = [1,2,3,4]
lst2 = [5,6,7,8]

for x in lst2:
  lst1.append(x)

print(lst1)
       

Output :

    
[1, 2, 3, 4, 5, 6, 7, 8]
    

You can also join two list with extend() in-built function.

Example 3 : Using Extend

    
# Merge lists using extend function

lst1 = [1,2,3,4]
lst2 = [5,6,7,8]

lst1.extend(lst2)
print(lst1)
       

Output :

    
[1, 2, 3, 4, 5, 6, 7, 8]
    

Sole purpose of extend is to add elements from one list to another list


Share your thoughts

Ask anything about this examples