본문으로 건너뛰기

How to merge two lists in Python

How to merge two lists in Python.

Here's a step-by-step tutorial on how to merge two lists in Python.

1: Create two lists​

First, let's create two separate lists that we want to merge. For example, let's create list1 and list2:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

2: Using the "+" operator​

One of the simplest ways to merge two lists in Python is by using the "+" operator. You can simply use the "+" operator to concatenate the two lists. Here's an example:

merged_list = list1 + list2
print(merged_list)

Output:

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

3: Using the extend() method​

Another way to merge two lists is by using the extend() method. The extend() method adds all the elements from one list to another list. Here's an example:

list1.extend(list2)
print(list1)

Output:

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

4: Using the append() method in a loop​

If you have multiple lists that you want to merge, you can use a loop and the append() method to merge them one by one. Here's an example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

merged_list = []
for lst in [list1, list2, list3]:
merged_list.extend(lst)

print(merged_list)

Output:

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

5: Using the itertools module​

The itertools module in Python provides a dedicated function called chain() that can be used to merge multiple lists. Here's an example:

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

merged_list = list(itertools.chain(list1, list2, list3))
print(merged_list)

Output:

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

That's it! You now know multiple ways to merge two or more lists in Python. Choose the method that suits your requirements best.