Python Tutorial

Joining Two Lists in Python

In Python, you may often need to combine two or more lists into a single list. This is a common operation, and Python provides several ways to accomplish this task. Let's explore the different methods you can use to join two lists.

Using the + Operator

The simplest way to join two lists is by using the + operator. This method creates a new list that contains all the elements from both the original lists.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]

Using the extend() Method

The extend() method adds all the elements from one list to the end of another list, modifying the original list in-place.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]
print(list2)  # Output: [4, 5, 6]

Note that the extend() method modifies the original list1, whereas the + operator creates a new list.

Using the list.append() Method in a Loop

You can also join two lists by iterating over one list and appending each element to the other list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
for item in list2:
    list1.append(item)
print(list1)  # Output: [1, 2, 3, 4, 5, 6]
print(list2)  # Output: [4, 5, 6]

This method modifies the original list1, similar to the extend() method.

Using the itertools.chain() Function

The itertools.chain() function from the Python standard library allows you to iterate over multiple iterables (such as lists) as if they were a single iterable.

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list(itertools.chain(list1, list2))
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]

This method creates a new list without modifying the original lists.

Using List Comprehension

You can also use a list comprehension to join two lists.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = [item for item in list1] + [item for item in list2]
print(combined_list)  # Output: [1, 2, 3, 4, 5, 6]

This method also creates a new list without modifying the original lists.

Choosing the Right Method

The method you choose to join two lists will depend on your specific use case and requirements. Here's a quick summary of the pros and cons of each method:

  • + operator: Simple and readable, but creates a new list.
  • extend() method: Modifies the original list, efficient for large lists.
  • Looping and append(): Modifies the original list, can be slower for large lists.
  • itertools.chain(): Creates a new list, efficient for large lists.
  • List comprehension: Creates a new list, can be more readable for simple cases.

Choose the method that best fits your needs, whether it's modifying the original lists, creating a new list, or optimizing performance for large datasets.