Append integer to beginning of list in Python
Solution 1
>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]
How it works:
array.insert(index, value)
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.
Solution 2
>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li # Don't use 'list' as variable name.
[5, 1, 2, 3]
Solution 3
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
Solution 4
Another way of doing the same,
list[0:0] = [a]
Solution 5
You can use Unpack list:
a = 5
li = [1,2,3]
li = [a, *li]
=> [5, 1, 2, 3]
gen
Updated on July 11, 2022Comments
-
gen almost 2 years
I have an integer and a list. I would like to make a new list of them beginning with the variable and ending with the list. Writing
a + list
I get errors. The compiler handlesa
as integer, thus I cannot use append, or extend either. How would you do this? -
Stefan Gruenwald over 9 yearsYou don't need the first 0. The colon already say that's before the start -- my_list[:0]=[a] does it.
-
Marcel Pfeiffer almost 9 yearsI just did some benchmarking.
li.insert(0, a)
is around 5x faster thanli = [a] + li
. Keep this in mind if you are doing this many times. -
unholysampler almost 9 years@MarcelPfeiffer It should be noted that
li.insert(0, a)
is mutatingli
.li = [a] + li
is creating a new instance will all of the values. This is an important distinction if other things have a reference to the list instance. -
Simon Steinberger over 8 yearsThe most efficient approach. Faster than [x]+[y]. See solutions here: stackoverflow.com/questions/8537916/…
-
Kemin Zhou over 7 yearsIt would be nice for python to add a list.push_front(item) function. This will be obvious and less error-prone.
-
Nullify over 7 years@BlackJack The question is about how to append integer to beginning of list. Whatever he describe that is not the right thing to follow. So why to guide him to take the wrong path? when there are better thing he can do for his requirement.
-
Nullify over 7 yearsIn that case question title should be different. Anyway there is no point of arguing, as the point is clear for both of us. Anyway thank you for pointing out. :)
-
god of llamas over 7 years@KeminZhou I'd prefer the name "prepend" as it follows naturally from "append" as "push_front" follows naturally from "push_back".
-
Kemin Zhou over 7 years@god of llamas, I agree with you. Shorter is always better.
-
Shejo284 about 7 yearsElegant solution!
-
cowbert over 6 years@Marcel Pfeiffer
collections.deque.appendleft()
should be even faster for large len(li). -
Mike Scotty about 6 yearsThis is already covered by the top rated answer. Please explain how this adds new information to the issue.
-
Erico9001 about 6 yearsO, it adds nothing
-
hacksoi almost 6 years@MarcelPfeiffer but that's not as pythonic!
-
Tatarize over 5 yearsSometimes switching structures isn't a thing you can do easily, and if you need to append a bunch of stuff to the front, you can call .reverse then add all the stuff to the end, then call reverse again. You'd get two O(n) operations but then use the O(1) adds of list.
-
xjcl about 5 yearsThis is interesting to know about, but I would avoid this because I think it might cause confusion.
-
Ravi R almost 5 yearsAnswer from @timgeb below makes sense esp. if there are too many inserts at front of list.
-
EMiller almost 5 yearsI hear by boost this answer to have more points than the selected one.
-
Tomato Master about 3 yearsuse append(), then reverse() function, as insert(0,val) function will take more time,because it will involve shifting of every element. i have experienced a time out issue due to insert
-
Nullify about 3 years@VishalYadav Can you please share the benchmarking?
-
Tomato Master about 3 years@Nullify , for example appending and reversing of 10000000 elements took almost 1.2 seconds which is equal to inserting 100 elements at 0th postion of a list.Below is the code to test, link will expire in a day , have a look ctxt.io/2/AACgpeUnFg
-
Charlie Parker almost 3 yearsin terms of computation time, is
new_list = [x] + your_list
less efficient thanyour_list.insert(x)
? -
Charlie Parker almost 3 yearsin terms of computation time, is
new_list = [x] + your_list
less efficient thanyour_list.insert(x)
? -
Charlie Parker almost 3 yearsin terms of computation time, is
new_list = [x] + your_list
less efficient thanyour_list.insert(x)
? -
pigi5 over 2 yearsThis is not elegant, it's unnecessarily confusing and difficult to read.
-
Kirti Purohit almost 2 yearsThank you so much. This made me pass my codeforces problem