Problem Formulation: How to insert an element at the first position of a list in Python?
list.insert(0, x) element to insert the element
x at the first position 0 in the list. All elements
j>0 will be moved by one index position to the right.
>>> lst = [5, 1, 3, 8, 7, 9, 2] >>> lst.insert(0, 42) >>> lst [42, 5, 1, 3, 8, 7, 9, 2]
You create the list
[5, 1, 3, 8, 7, 9, 2] and store it in the variable
Next, insert the new element
42 to the first position in the list with index 0.
💡 Note: Python uses zero-based indexing so the first position has index 0.
The resulting list has 8 elements instead of only 7. The new element 42 is at the head of the list. All remaining elements are shifted by one position to the right.
To dive deeper into the very important
list.insert() method, I’d recommend you watch my full explainer video here:
Note that some people recommend inserting an element at the first position of a list like so:
>>> lst = [1, 2, 3] >>> lst = ['new'] + lst >>> lst ['new', 1, 2, 3]
While the output looks the same, this doesn’t actually solve the problem because the list concatenation operator
list_1 + list_2 creates a new list with the elements of two existing lists.
The original lists remain unchanged.
Only by assigning it to the variable
lst, you overwrite it. However, if another variable would point to the old list, this option based on list concatenation wouldn’t work because the old list remains unchanged.
>>> lst_1 = [1, 2, 3] >>> lst_2 = lst_1 >>> lst_2 = ['new'] + lst_2
In this example, you create two lists
lst_2 both referring to the same list object in memory.
You try to insert the new element at the beginning of the list using the problematic method. And you obtain a clash—both lists refer to different objects in memory!
>>> lst_2 ['new', 1, 2, 3] >>> lst_1 [1, 2, 3]
list.insert(0, 'new') method is superior to list concatenation to insert an element at a given position in the list.
>>> lst_1 = [1, 2, 3] >>> lst_2 = lst_1 >>> lst_2.insert(0, 'new') >>> lst_1 ['new', 1, 2, 3] >>> lst_2 ['new', 1, 2, 3]
Both variables now refer to the same, changed list object.
Where to Go From Here?
If you’re interested in learning more about the vital list data structure in Python, feel free to check out our premium course at the Finxter Computer Science Academy:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.