How do I concatenate two lists in Python?
How can you combine two lists into one in Python? What methods are available to merge lists efficiently while preserving their order? Learn how to concatenate lists using different techniques, from simple operators to built-in functions.
To concatenate two lists in Python, there are several straightforward methods you can use. Combining lists involves merging the elements of one list into another, which can be achieved with basic operators or functions. Here’s how you can do it:
Methods to concatenate lists:
Using the + Operator:
The + operator is the simplest and most common way to concatenate two lists. It creates a new list by joining both lists.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]
Using the extend() Method:
The extend() method adds all elements of one list to another in place, modifying the original list.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Using itertools.chain():
The itertools.chain() function from the itertools module can be used to concatenate lists without creating a new list in memory.
Example:
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(itertools.chain(list1, list2))
print(result) # Output: [1, 2, 3, 4, 5, 6]
Summary:
- + Operator: Easy and simple, creates a new list.
- extend(): Modifies the first list by adding elements from the second.
- itertools.chain(): Efficient for large lists, doesn’t create a new list.