October 15, 2024

How to Add Two Lists in Python

In Python, you can add two lists together by concatenating them, which creates a new list containing all the elements from both lists. There are several ways to do this, depending on your specific needs.

Method 1: Using the + Operator

The simplest way to add two lists together is by using the + operator. This operator concatenates the lists, creating a new list with elements from both lists.

Example:

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Add the lists together
result = list1 + list2

print(result)
    

Output:

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

Method 2: Using the extend() Method

The extend() method appends all elements from one list to another list. This modifies the original list in place.

Example:

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Extend list1 by adding elements from list2
list1.extend(list2)

print(list1)
    

Output:

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

Method 3: Using a List Comprehension

You can also add two lists together using a list comprehension, which allows you to combine elements from both lists into a new list.

Example:

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Combine the lists using a list comprehension
result = [x for x in list1] + [y for y in list2]

print(result)
    

Output:

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

Method 4: Using the itertools.chain() Function

The itertools.chain() function from the itertools module allows you to concatenate multiple iterables, including lists, into a single iterable.

Example:

import itertools

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Combine the lists using itertools.chain
result = list(itertools.chain(list1, list2))

print(result)
    

Output:

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

Conclusion

Adding two lists together in Python is a simple task that can be accomplished in multiple ways, depending on whether you want to create a new list or modify an existing one. The + operator is the most straightforward approach, while extend(), list comprehensions, and itertools.chain() provide additional flexibility.