0
0
PythonHow-ToBeginner · 3 min read

How to Merge Two Lists in Python: Simple Methods Explained

You can merge two lists in Python by using the + operator to concatenate them, or by using the list.extend() method to add elements from one list to another. Another modern way is to use the unpacking syntax [ *list1, *list2 ] to create a new merged list.
📐

Syntax

Here are common ways to merge two lists list1 and list2 in Python:

  • merged = list1 + list2: Creates a new list by joining both lists.
  • list1.extend(list2): Adds all elements of list2 to the end of list1 (modifies list1).
  • merged = [*list1, *list2]: Uses unpacking to create a new merged list.
python
merged = list1 + list2
list1.extend(list2)
merged = [*list1, *list2]
💻

Example

This example shows how to merge two lists using the + operator, extend() method, and unpacking syntax.

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

# Using + operator
merged_plus = list1 + list2
print('Using +:', merged_plus)

# Using extend() method
list1_copy = list1.copy()  # copy to keep original list1
list1_copy.extend(list2)
print('Using extend():', list1_copy)

# Using unpacking
merged_unpack = [*list1, *list2]
print('Using unpacking:', merged_unpack)
Output
Using +: [1, 2, 3, 4, 5, 6] Using extend(): [1, 2, 3, 4, 5, 6] Using unpacking: [1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

Some common mistakes when merging lists include:

  • Using extend() but expecting a new list returned (it returns None because it modifies the list in place).
  • Trying to add lists with append() which adds the entire second list as a single element.
  • Modifying the original list unintentionally when using extend().
python
list1 = [1, 2]
list2 = [3, 4]

# Wrong: append adds list2 as one element
list1_wrong = list1.copy()
list1_wrong.append(list2)
print('Using append:', list1_wrong)  # Output: [1, 2, [3, 4]]

# Right: use extend to add elements
list1_right = list1.copy()
list1_right.extend(list2)
print('Using extend:', list1_right)  # Output: [1, 2, 3, 4]
Output
Using append: [1, 2, [3, 4]] Using extend: [1, 2, 3, 4]
📊

Quick Reference

Summary of methods to merge two lists:

MethodDescriptionReturns New List?Modifies Original?
list1 + list2Concatenates two listsYesNo
list1.extend(list2)Adds elements of list2 to list1NoYes
[*list1, *list2]Unpacks both lists into a new listYesNo
list1.append(list2)Adds list2 as a single elementNoYes

Key Takeaways

Use + or unpacking [*list1, *list2] to create a new merged list without changing originals.
Use list1.extend(list2) to add elements to an existing list in place.
Avoid using append() to merge lists because it nests the second list as one element.
Remember extend() returns None and modifies the list directly.
Copy lists if you want to keep the original lists unchanged when merging.