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.

The code snippet above should print the following…

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.

The code snippet above should print the following…

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

The code snippet above should print the following…

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…

The code snippet above prints the following…

Using the insert method can do it as well…

The code snippet above should print the following…

We can also concatenate them as follows…

The code snippet above should print the following…

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

The code snippet above should print the following…

We can also do that using extend…

The code snippet above should print the following…

References

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

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *