How to Insert at the First Position of a List in Python

https://blog.finxter.com/wp-content/uploads/2021/05/insert_list_first_pos.jpg

Problem Formulation: How to insert at the first position of a list in Python?

How to Insert at the First Position of a List in Python

Solution:

Use the 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 lst. Now, you insert the new element 42 to the first position in the list with index 0. Note that 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 to insert 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_1 and 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]

Thus, the 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.

The post How to Insert at the First Position of a List in Python first appeared on Finxter.Finxter