The Most Effective Way to Add an Element at the Beginning of a List in Python
Python makes it very easy to append to the front of a list. This can be done with the insert() function, which takes two arguments …
Python makes it very easy to append to the front of a list. This can be done with the insert() function, which takes two arguments
Python lists are ordered collections of items. The most effective way to append an item at the beginning of a list is by using Python’s built-in insert()
method. The insert() function adds an item at a specific index in the list. If you specify ‘0’, it will add this element at the beginning, effectively appending it to the front of the list.
Here’s how to do that:
list = ['item1', 'item2'] # Initialize list with some items
list.insert(0,'new_item') # Insert new item in the front
print(list) # Prints: ['new_item', 'item1', 'item2']
In this code, list.insert(0,'new_item')
is adding a new element (‘new_item’) to the beginning of the list. Python interprets ‘0’ as the first index in the list (the front), and therefore adds the item there.