Explain Codes LogoExplain Codes Logo

What is the syntax to insert one list into another list in Python?

python
list-insertion
python-lists
list-merging
Anton ShumikhinbyAnton Shumikhin·Mar 12, 2025
TLDR

Insert list2 into list1 at a specified position by assigning list1[start:start] = list2:

list1 = [1, 2, 5] list2 = [3, 4] list1[2:2] = list2 print(list1) # [1, 2, 3, 4, 5] So, easy, huh?

Let's digress and check the tricks in inserting lists properly.

Append, extend or insert: The Trinity

Python offers a few ways to insert lists, each doing a unique job.

Append vs. extend: Not all habits are bad

  • list.append(x) — need to remember 'x' as is? x gets appended as a single item and if x is a list, it fits in as a tiny nested list.
  • list.extend(iterable) — more into expansion? Extends the list with elements from iterable.

The insert way, or: Insertion, my dear Watson

  • list.insert(i, x) — performs surgery to fit x at index i, as one single operation!
# list.insert(i, x) demonstration, hold the applause... list1 = [1, 2, 5] list2 = [3, 4] list1.insert(2, list2) print(list1) # [1, 2, [3, 4], 5]

Time for a slicing spree: The slice and stitch

For a specific insertion point, play with slicing to sew-in list2 into a snuggly fit. No nesting!

# Let's slice and stitch! list1[start:end] = list2

Bouncer at the gate: Unique club members only

If you're like me and love unique things, subtract your list from a set before extending. This one's for the unique crowd:

# Handpicked guests only, please... list1.extend(set(list2) - set(list1))

Merge 'em all: The list merging juggernaut

These merging techniques can prove useful.

Concatenation: Ready to hold hands?

Concatenation is like holding hands, the lists come together, end-to-end:

# Holding hands... new_list = list1 + list2 # Aren't they cute together?

Slice till you make it: Shape up with replacement

Reshape the list, replace a range with another list:

# Slice, dice, replace! list1[1:3] = list2 # Out with the old, in with the new!

Big lists: Go hard or go home

Got a big list? extend or slice. They're like the memory gym — preserving memory and keeping things fit.

Missteps: A surgery gone wrong

Common missteps and how to tread carefully:

  • If you sign-up for a flat list, append could nest you deep.
  • Remember, insert, append, and extend alter the list in situ.
  • The + cure can come with a memory-cost side effect.