Append integer to beginning of list in Python
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Question
00:19 Accepted answer (Score 1194)
00:57 Answer 2 (Score 592)
01:12 Answer 3 (Score 133)
02:06 Answer 4 (Score 54)
02:18 Thank you
--
Full question
https://stackoverflow.com/questions/1791...
Answer 2 links:
[O(n) operation]: https://wiki.python.org/moin/TimeComplex...
[deque]: https://docs.python.org/2/library/collec...
--
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]