How to Prepend to List in Python
Prepend to List in Python
To prepend an element to list properly, use the collections.deque.appendleft() method. In this approach, a list can be converted to deque, and then the appendleft() function can be used to perform the push-like operation from the front of the double-ended queue.
from collections import deque listA = [2, 3, 4] print("Original list: ", listA) listA = deque(listA) listA.appendleft(1) print("After prepending: ", list(listA))
Original list: [2, 3, 4] After prepending: [1, 2, 3, 4]
If you insert at the front of a list, python has to move all the other items one space forwards; lists can’t “make space at the front”. The collections.deque(double-ended queue) supports “making space at the front” and is much faster in this case.
Prepend to List in Python using list.insert()
To prepend to a list in Python, use the list.insert() method with index set to 0, which adds an element at the beginning of the list. The insert() is a built-in Python function that inserts an item to the list at the given index.
listA = [2, 3, 4] listA.insert(0, 1) print(listA)
[1, 2, 3, 4]
You can see that we inserted element 1 at the beginning of the list.
The first argument is the index of the element before which to insert, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x).
Negative values are treated as being relative to the end of the array.
To append an element at the end of the list, use the list.append() method. The list append() is a built-in Python method that adds a single element to the existing list. The list.append() method takes an element as an argument and doesn’t return a new list; instead, it modifies the original list.
listA = [2, 3, 4] listA.append(1) print(listA)
[2, 3, 4, 1]
That is it for pretending an element to the list in Python.