How do I concatenate two lists in Python?

To concatenate (combine) two lists in Python, you can use multiple approaches. Here are the most common and efficient methods:

1. Using the + Operator

Creates a new list containing elements of both lists.
Original lists remain unchanged.

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

2. Using extend() Method

Modifies the original list by appending elements of the second list.
No new list is created.

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

3. Using += Operator

Similar to extend()—modifies the original list in-place.

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

4. Using List Unpacking (Python 3.5+)

Works like the + operator but with unpacking syntax (*).

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

5. Using itertools.chain()

Efficient for large lists or iterators (returns an iterator).

import itertools

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

Key Differences

MethodModifies Original List?Creates New List?Use Case
+Combine lists without mutation.
extend()Modify original list in-place.
+=Short syntax for in-place extend.
Unpacking (*)Clean syntax (Python 3.5+).
itertools.chain()Memory-efficient for large data.

Example: Nested Lists

To concatenate nested lists (flatten them), use a list comprehension:

nested = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested for item in sublist]
print(flattened)  # Output: [1, 2, 3, 4, 5, 6]

Performance Notes

  • + vs extend(): Use extend() or += for large lists (avoids creating temporary copies).
  • itertools.chain(): Best for iterators/lazy evaluation (does not store the full list in memory).

Choose the method that best fits your use case!

Leave a Reply

Your email address will not be published. Required fields are marked *