Python program to concatenate two lists














































Python program to concatenate two lists



Python program to concatenate two lists


There are various ways to concatenate two lists.

METHOD 1:

Using + operator:

Example:
list1 = ['a','b','c','d'] 
list2 = ['e','f','g','h'] 
  
# using + operator 
list1 = list1 + list2 
print ("Concatenated list using + : "+ str(list1)) 

Output:
Concatenated list using + : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


METHOD 2:

Using 'list.extend' function:

Example:
list1 = ['a','b','c','d'] 
list2 = ['e','f','g','h'] 
  
# using list.extend() 
list1.extend(list2) 
print ("Concatenated list using list.extend() : " + str(list1)) 

Output:
Concatenated list using list.extend() : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


METHOD 3:

Using * operator:

Example:
list1 = ['a','b','c','d'] 
list2 = ['e','f','g','h'] 
  
# using * operator
result = [*list1, *list2] 
  
print ("Concatenated list using * operator : " + str(result)) 

Output:
Concatenated list using * operator : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


METHOD 4:

Using 'append' function:

Example:
list1 = ['a','b','c','d'] 
list2 = ['e','f','g','h'] 
  
# using append function
for i in list2 : 
    list1.append(i) 
   
print ("Concatenated list using append method : " + str(list1)) 

Output:
Concatenated list using append method : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


METHOD 5:

Using itertools.chain:

Example:

import itertools

list1 = ['a','b','c','d']
list2 = ['e','f','g','h']

# using itertools.chain function

res=list(itertools.chain(list1,list2))
print ("Concatenated list using itertools : "+ str(res))


Output:
Concatenated list using itertools : ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


Comments