1

How do I add a new element in a list in python? For example, there is a list

lst = [1, 2, 3, 4]

I want to update the list and insert 10. it will become

lst = [10, 1, 2, 3]

which means the last element disappears and the older one moves back.

martineau
  • 119,623
  • 25
  • 170
  • 301
Comp
  • 105
  • 8

3 Answers3

4

You can use the list methods insert and pop:

lst.insert(0, 10)  # lst is now [10, 1, 2, 3, 4]
lst.pop()  # lst is now [10, 1, 2, 3]

Note: Inserting items at the beginning of a Python list is not very efficient because Python lists are array lists. Instead you can use a deque(linked list) from the collections module. This will also allow you to provide a max size for the deque so the end element will always be bumped out:

from collections import deque

lst2 = deque(lst, maxlen=4)
lst2.appendleft(10)  # lst2 is now [10, 1, 2, 3]
Alex
  • 18,484
  • 8
  • 60
  • 80
1

You can use:

lst = [1, 2, 3, 4]
new_lst = [10] + lst[:-1]
# [10, 1, 2, 3]

This adds new element, here 10, at first position and takes the list excluding the last element.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

You may want to use a bounded deque instead of a list.

>>> from collections import deque
>>> d = deque([1,2,3,4], 4)
>>> d
deque([1, 2, 3, 4], maxlen=4)
>>> d.appendleft(10)
>>> d
deque([10, 1, 2, 3], maxlen=4)

A deque (double-ended queue) is like a queue, but rather than being optimized for appending to one end and removing from the other, it is optimized for appending and removing from either end. Setting a maximum length ensures that if you add an element to one end of a full deque, the element on the other end is automatically removed.

chepner
  • 497,756
  • 71
  • 530
  • 681