How to merge two lists in Python
In this tutorial, we are going to see different ways to merge or combine two or more lists.
- Using the + operator
- Using the extend() method
How to merge two lists in Python using the + operator
# Lists list1 = ['Python', 'Java', 'C', 'C++', 'PHP'] list2 = ['blue', 'green', 'red'] # Merge list1 and list2 list3 = list1 + list2 #Print the list print(list3)
Output:
['Python', 'Java', 'C', 'C++', 'PHP', 'blue', 'green', 'red']
How to merge two lists in Python using the extend() method
# Lists list1 = ['Python', 'Java', 'C', 'C++', 'PHP'] list2 = ['blue', 'green', 'red'] # Merge list1 and list2 list1.extend(list2) #Print the list print(list1)
Output:
['Python', 'Java', 'C', 'C++', 'PHP', 'blue', 'green', 'red']
Merge multiple lists using the + operator
# Lists list1 = ['Python', 'Java', 'C', 'C++', 'PHP'] list2 = ['blue', 'green', 'red'] list3 = [1, 2, 3] # Merge list1, list2 and list3 list4 = list1 + list2 + list3 #Print the list print(list4)
Output:
['Python', 'Java', 'C', 'C++', 'PHP', 'blue', 'green', 'red', 1, 2, 3]