Python insert list into list at index

Introduction

This is a frequently asked question in Python despite its simplicity. In the code snippets below, we will provide straightforward examples to demonstrate how to embed a list within another list at the beginning, middle and end. Let us start with the first case...

Python insert list into list at beginning

The list object has an insert method that can be used to insert another list at any given position, in this case position 0.

# Define a list
A = [3, 4, 5]
# Define another list
B = [1, 2]
# Insert B into A
A.insert(0, B)
# Print A
print(A)

The code snippet above should print the following…

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

Python insert list into list at position

Similarly, we can use the same technique to insert the list at the middle by changing the index.

# Define a list
A = [1, 2, 5]
# Define another list
B = [3, 4]
# Insert B into A
A.insert(2, B)
# Print A
print(A)

The code snippet above should print the following…

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

We can also use Python list slicing to accomplish the same task. Let us see how...

# Define a list
A = [1, 2, 5]
# Define another list
B = [3, 4]
# Insert B into A
A[2:1] = [B]
# Print A
print(A)

The code snippet above should print the following…

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

Python insert list into list at end

To insert an item at the end of the list we can use the append method. Take a look...

# Define a list
A = [1, 2, 3]
# Define another list
B = [4, 5]
# Insert B into A
A.append(B)
# Print A
print(A)

The code snippet above prints the following...

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

Using the insert method can do it as well...

# Define a list
A = [1, 2, 3]
# Define another list
B = [4, 5]
# Insert B into A
A.insert(len(A), B)
# Print A
print(A)

The code snippet above should print the following…

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

We can also concatenate them as follows...

# Define a list
A = [1, 2, 3]
# Define another list
B = [4, 5]
# Insert B into A
C = A + [B]
# Print C
print(C)

The code snippet above should print the following…

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

but if we just want to add the elements without keeping the list...

# Define a list
A = [1, 2, 3]
# Define another list
B = [4, 5]
# Insert B into A
C = A + B
# Print C
print(C)

The code snippet above should print the following…

[1, 2, 3, 4, 5]

We can also do that using extend…

# Define a list
A = [1, 2, 3]
# Define another list
B = [4, 5]
# Insert B into A
A.extend(B)
# Print A
print(A)

The code snippet above should print the following…

[1, 2, 3, 4, 5]

References

Thanks for reading. Please use the comments section below for questions and feedback.

Leave a Reply