Join Lists

Joining lists means combining two or more lists into one. Python provides multiple ways to join lists, and each method behaves differently.
Choosing the right method is important for performance, readability, and correctness.

Join Lists Using + Operator

The + operator creates a new list by concatenating lists.
python
list1 = [1, 2]
list2 = [3, 4]

result = list1 + list2
print(result)
python
a = ["apple"]
b = ["banana", "cherry"]
print(a + b)
Original lists remain unchanged.

Join Lists Using extend()

The extend() method adds elements of one list to another list.
python
list1 = [1, 2]
list2 = [3, 4]

list1.extend(list2)
print(list1)
list2 remains unchanged.

Join Lists Using append() (Nested Result)

Using append() adds the entire list as a single element.
python
list1 = [1, 2]
list2 = [3, 4]

list1.append(list2)
print(list1)
This creates a nested list.

Join Lists Using Loop

python
list1 = [10, 20]
list2 = [30, 40]

for item in list2:
    list1.append(item)

print(list1)
Useful when you need custom logic while joining.

Join Lists Using List Comprehension

python
list1 = [1, 2]
list2 = [3, 4]

result = [x for x in list1] + [y for y in list2]
print(result)

Join Lists Using itertools.chain()

This method is memory-efficient for large lists.
python
from itertools import chain

list1 = [1, 2]
list2 = [3, 4]

result = list(chain(list1, list2))
print(result)

Join More Than Two Lists

python
a = [1, 2]
b = [3, 4]
c = [5, 6]

result = a + b + c
print(result)
python
a.extend(b)
a.extend(c)
print(a)

Join Lists with Different Data Types

python
list1 = [1, 2]
list2 = ["a", "b"]

print(list1 + list2)

Common Mistakes

Expecting extend() to Return a List

python
result = list1.extend(list2)
print(result)
extend() returns None.

Using append() Instead of extend()

python
list1.append(list2)
Creates nested list unintentionally.

Performance Comparison

  • extend() is faster than + for large lists
  • + creates a new list
  • append() should not be used for joining lists

Summary

  • + joins lists and creates a new list
  • extend() modifies the existing list
  • append() creates a nested list
  • Loops allow custom joining
  • itertools.chain() is memory-efficient
  • Choose method based on requirement