How to Combine Two Lists in Python

To combine two lists in Python, you can use the + operator, the extend() function, the itertools.chain() function, or the zip() function.

The following examples show how to combine two lists in Python.

Using + Operator

We can use the + operator to combine two lists.

Suppose we have the following lists:

# Create two lists
list1 = ['Anita', 'Sanika', 'Shubham']
list2 = ['Gaurav', 'Namita', 'Sushma', 'Anju']

# Combine the two lists using the + operator
combined_list = list1 + list2

# Show combined list
print("Combined list:", combined_list)

Output: 👇️

Combined list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'Anju']

In this example, we use the + operator to combine list1 and list2 into a single list combined_list.

Using extend() Function

We can use the extend() function to combine two lists.

Suppose we have the following lists:

# Create two lists
list1 = ['Anita', 'Sanika', 'Shubham']
list2 = ['Gaurav', 'Namita', 'Sushma', 'Anju']

# Combine the two lists using the extend() function
list1.extend(list2)

# Show combined list
print("Combined list:", list1)

Output: 👇️

Combined list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'Anju']

In this example, we use the extend() function to add each element of list2 to list1.

Using itertools.chain() Function

We can use the itertools.chain() function to combine two lists.

Suppose we have the following lists:

import itertools

# Create two lists
list1 = ['Anita', 'Sanika', 'Shubham']
list2 = ['Gaurav', 'Namita', 'Sushma', 'Anju']

# Combine the two lists using the itertools.chain() function
combined_list = list(itertools.chain(list1, list2))

# Show combined list
print("Combined list:", combined_list)

Output: 👇️

Combined list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'Anju']

In this example, we use the itertools.chain() function to combine list1 and list2 into a single list combined_list.

Using zip() Function

We can use the zip() function to combine two lists.

Suppose we have the following lists:

# Create two lists
list1 = ['Anita', 'Sanika', 'Shubham']
list2 = ['Gaurav', 'Namita', 'Sushma']

# Combine the two lists using the zip() function
combined_list = [i for sublist in zip(list1, list2) for i in sublist]

# Show combined list
print("Combined list:", combined_list)

Output: 👇️

Combined list: ['Anita', 'Gaurav', 'Sanika', 'Namita', 'Shubham', 'Sushma']

In this example, we use the zip() function to combine list1 and list2 into a single list combined_list by interleaving their elements.

Conclusion

We can use the + operator, the extend() function, the itertools.chain() function, and the zip() function to combine two lists in Python. These methods provide a convenient way to merge lists in Python.