The Python Oracle

Append integer to beginning of list in Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 Append Integer To Beginning Of List In Python
00:13 Answer 1 Score 606
00:22 Accepted Answer Score 1276
00:51 Answer 3 Score 55
00:59 Answer 4 Score 134
01:45 Thank you

--

Full question
https://stackoverflow.com/questions/1791...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #prepend

#avk47



ACCEPTED ANSWER

Score 1276


>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]

How it works:

list.insert(index, value)

Insert an item at a given position. The first argument is the index of the element before which to insert, so xs.insert(0, x) inserts at the front of the list, and xs.insert(len(xs), x) is equivalent to xs.append(x). Negative values are treated as being relative to the end of the list.




ANSWER 2

Score 606


>>> x = 42
>>> xs = [1, 2, 3]
>>> [x] + xs
[42, 1, 2, 3]

Note: don't use list as a variable name.




ANSWER 3

Score 134


Note that if you are trying to do that operation often, especially in loops, a list is the wrong data structure.

Lists are not optimized for modifications at the front, and somelist.insert(0, something) is an O(n) operation.

somelist.pop(0) and del somelist[0] are also O(n) operations.

The correct data structure to use is a deque from the collections module. deques expose an interface that is similar to those of lists, but are optimized for modifications from both endpoints. They have an appendleft method for insertions at the front.

Demo:

In [1]: lst = [0]*1000
In [2]: timeit -n1000 lst.insert(0, 1)
1000 loops, best of 3: 794 ns per loop
In [3]: from collections import deque
In [4]: deq = deque([0]*1000)
In [5]: timeit -n1000 deq.appendleft(1)
1000 loops, best of 3: 73 ns per loop



ANSWER 4

Score 55


Another way of doing the same,

list[0:0] = [a]