Skip to content

Python add to beginning of list

  • by

You can use the insert() method or the + Operator to add to the beginning of the list in Python. The insert() function inserts an element to the given index of an existing list.

insert(idx, value)

Using the + operator on two or more lists combines them in the specified order. If you add list1 + list2 together, then it concatenates all the elements from list2 after the last element of list1.

Python add to the beginning of the list

Simple example code append an element to the front of a list in Python. Notice the to_insert variable is encapsulated with square brackets [].

lst = [1, 2, 3]

# insert 24 at 0 index
lst.insert(0, 24)
print(lst)

# concatenates
lst = [100] + lst
print(lst)

Output:

Python add to beginning of list

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.

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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