Append an item to the front of list in Python

In this article, we will introduce the method of adding data to the front of a list.

1. list.insert(index, item)

insert(index, item) adds the item to the argument index. Therefore, to add an item to the beginning of a list, you can do insert(0, item).

list = [2, 9, 3]
list.insert(0, 'a')
print(list)

Output:

['a', 2, 9, 3]

2. collections.deque()

You can also use collections.deque(). It returns a deque based on the list passed in as an argument. And, deque.appendleft(item) adds an item to the front of the deque.

The example below first converts a list to a deque, adds an item to the front, and then converts the deque back to a list.

from collections import deque

my_list = [2, 9, 3]
deq = deque(my_list)
deq.appendleft('a')

new_list = list(deq)
print(new_list)

Output:

['a', 2, 9, 3]

3. deque.append()

Note that deque also provides append(), which adds data to the end of the list.

my_list = [2, 9, 3]
deq = deque(my_list)
deq.appendleft('a')
deq.append('b')

print(list(deq))

Output:

['a', 2, 9, 3, 'b']

4. deque.pop(), deque.popleft()

deque.pop() removes the last item, and deque.popleft() removes the item at the front.

my_list = [2, 9, 3]
deq = deque(my_list)
deq.pop()
print(list(deq))

deq.popleft()
print(list(deq))

Output:

[2, 9]
[9]
codechachaCopyright ©2019 codechacha