Insert list in another list Python (original) (raw)

Last Updated : 01 Feb, 2025

We are given two lists, and our task is to insert the elements of the second list into the first list at a specific position. **For example, given the lists a = [1, 2, 3, 4] and b = [5, 6], we want to insert list 'b' into 'a' at a certain position, resulting in the combined list a = [1, 2, 5, 6, 3, 4].

Using list.insert()

insert() method allows us to insert an element at a specific index in the list. By looping through the elements of the second list, we can insert them one by one into the first list at the desired position.

Python `

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

Loop through each element in b and insert it into a at the specified index

for item in b: a.insert(index, item) # Insert item from b at the specified index index += 1 # Increment index to add next item after the previous one

print(a)

`

**Explanation:

Let's explore some more ways to insert on list in another list.

Table of Content

Using List Slicing

List Slicing method allows us to split the first list and insert the second list into the desired position.

Python `

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

Slicing a before and after the index, then inserting b between

a = a[:index] + b + a[index:]

print(a)

`

**Explanation:

Using extend()

extend() method can be used when we want to add all elements from the second list to the first list. This method is useful if we want to add the elements to the end or any specific index using slicing.

Python `

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

Insert elements from b into a using slicing

a[index:index] = b

print(a)

`

**Explanation:

itertools.chain() function can be used to combine multiple iterables into a single one. By using chain(), we can merge both lists efficiently.

Python `

import itertools

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

Use itertools.chain() to combine the three parts of the list

a = list(itertools.chain(a[:index], b, a[index:]))

print(a)

`

**Explanation: We use itertools.chain() to merge the parts of 'a' before and after the insertion index, along with the list 'b'.

Using append() and reverse()

This method first appends all elements from 'b' to the end of 'a' and then reverses the lists for proper positioning.

Python `

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

Extend a with b, then reverse the remaining part of a after the insert index

a.extend(b) a[index + len(b):] = reversed(a[index + len(b):]) # Reverse the rest of the list

Insert b into a at the specified index

a[index:index] = b

print(a)

`

Output

[1, 2, 5, 6, 3, 4, 6, 5]

**Explanation: We first extend 'a' with 'b', then we reverse the remaining portion of the list to keep the original order intact after inserting 'b'.