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 adds to the beginning of the list
A simple example code appends 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:
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.
Using prepend()
method (if available):
# Note: Python does not have a built-in prepend method, but you can define one for convenience.
def prepend(lst, element):
return [element] + lst
my_list = [2, 3, 4, 5]
element_to_add = 1
my_list = prepend(my_list, element_to_add)
print(my_list)
In this example, a custom prepend()
function is defined, which creates a new list with the desired element added at the beginning.
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.