Python – Join Lists
Joining or combining lists in Python is a common operation. Whether you're merging datasets or simply appending items, Python provides multiple ways to join lists efficiently.
1. Using the +
Operator
The most straightforward way to join two lists.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
combined = list1 + list2
print(combined)
Output:
['a', 'b', 'c', 1, 2, 3]
Creates a new list. Original lists are unchanged.
2. Using extend()
Method
Appends all elements of one list to the end of another (modifies the original list).
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output:
['a', 'b', 'c', 1, 2, 3]
Efficient when you want to update the first list directly.
3. Using a Loop (for
)
Join lists manually by looping through one and appending to another.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for item in list2:
list1.append(item)
print(list1)
Output:
['a', 'b', 'c', 1, 2, 3]
Useful when you want custom logic during the merge.
4. Using List Comprehension
Another flexible and Pythonic method to join lists.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
combined = [item for item in list1] + [item for item in list2]
print(combined)
Output:
['a', 'b', 'c', 1, 2, 3]
Handy if you want to filter or transform while joining.
5. Using itertools.chain()
For large lists or performance-critical cases, use itertools
.
Example:
import itertools
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
combined = list(itertools.chain(list1, list2))
print(combined)
Output:
['a', 'b', 'c', 1, 2, 3]
Efficient for joining many iterables at once.
Summary Table
Method | Description | In-Place | Returns New List |
---|---|---|---|
+ operator | Combines lists into a new one | ❌ | ✅ |
extend() | Appends to original list | ✅ | ❌ |
for loop + append() | Manual control, flexible | ✅ | ❌ |
List comprehension | Join with transformation | ❌ | ✅ |
itertools.chain() | Best for performance and memory | ❌ | ✅ |