Append integer to beginning of list in Python [duplicate]
>>>var=7>>>array = [1,2,3,4,5,6]>>>array.insert(0,var)>>>array[7, 1, 2, 3, 4, 5, 6]
How it works:
Insert an item at a given position. 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.
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.
del somelist 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.
In : lst = *1000In : timeit -n1000 lst.insert(0, 1)1000 loops, best of 3: 794 ns per loopIn : from collections import dequeIn : deq = deque(*1000)In : timeit -n1000 deq.appendleft(1)1000 loops, best of 3: 73 ns per loop