765

How do I prepend an integer to the beginning of a list?

[1, 2, 3]  ⟶  [42, 1, 2, 3]
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
gen
  • 9,528
  • 14
  • 35
  • 64

10 Answers10

1235
>>> 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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Kousik
  • 21,485
  • 7
  • 36
  • 59
  • 28
    The most efficient approach. Faster than [x]+[y]. See solutions here: http://stackoverflow.com/questions/8537916/whats-the-idiomatic-syntax-for-prepending-to-a-short-python-list – Simon Steinberger Oct 19 '15 at 21:41
  • 1
    @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. – Kousik Oct 19 '16 at 08:19
  • 1
    In 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. :) – Kousik Oct 19 '16 at 13:00
  • use 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 – Tomato Master Feb 05 '21 at 14:09
  • @VishalYadav Can you please share the benchmarking? – Kousik Feb 08 '21 at 10:21
  • @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 https://ctxt.io/2/AACgpeUnFg – Tomato Master Feb 10 '21 at 12:23
  • in terms of computation time, is `new_list = [x] + your_list` less efficient than `your_list.insert(x)`? – Charlie Parker Jul 21 '21 at 17:16
598
>>> x = 42
>>> xs = [1, 2, 3]
>>> [x] + xs
[42, 1, 2, 3]

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 400
    I just did some benchmarking. `li.insert(0, a)` is around 5x faster than `li = [a] + li`. Keep this in mind if you are doing this many times. – Marcel Pfeiffer May 26 '15 at 08:09
  • 101
    @MarcelPfeiffer It should be noted that `li.insert(0, a)` is mutating `li`. `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. – unholysampler May 31 '15 at 20:48
  • 6
    It would be nice for python to add a list.push_front(item) function. This will be obvious and less error-prone. – Kemin Zhou Sep 18 '16 at 03:21
  • 23
    @KeminZhou I'd prefer the name "prepend" as it follows naturally from "append" as "push_front" follows naturally from "push_back". – god of llamas Nov 15 '16 at 00:29
  • 1
    @god of llamas, I agree with you. Shorter is always better. – Kemin Zhou Nov 15 '16 at 06:05
  • 1
    @Marcel Pfeiffer `collections.deque.appendleft()` should be even faster for large len(li). – cowbert Sep 13 '17 at 17:55
  • @MarcelPfeiffer but that's not as pythonic! – hacksoi May 05 '18 at 09:22
  • Answer from @timgeb below makes sense esp. if there are too many inserts at front of list. – Ravi R May 10 '19 at 06:24
  • in terms of computation time, is `new_list = [x] + your_list` less efficient than `your_list.insert(x)`? – Charlie Parker Jul 21 '21 at 17:16
133

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
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 6
    Sometimes 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. – Tatarize Oct 01 '18 at 20:22
  • 1
    in terms of computation time, is `new_list = [x] + your_list` less efficient than `your_list.insert(x)`? – Charlie Parker Jul 21 '21 at 17:16
  • That's not the question though. Keep in mind, sometimes you didn't create the list and it came from some other team/library where you'd like to append in the front. There are times when you have no control over externalities. :-) – Neil Oct 02 '22 at 23:57
54

Another way of doing the same,

list[0:0] = [a]
v2b
  • 1,436
  • 9
  • 15
24

You can use Unpack list:

a = 5

li = [1,2,3]

li = [a, *li]

=> [5, 1, 2, 3]

HoangYell
  • 4,100
  • 37
  • 31
12

Based on some (minimal) benchmarks using the timeit module it seems that the following has similar if not better performance than the accepted answer

new_lst = [a, *lst]

As with [a] + list this will create a new list and not mutate lst.

If your intention is to mutate the list then use lst.insert(0, a).

Dovi Salomon
  • 159
  • 1
  • 5
11
list_1.insert(0,ur_data)

make sure that ur_data is of string type so if u have data= int(5) convert it to ur_data = str(data)

sahil panindre
  • 184
  • 2
  • 6
5

Alternative:

>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

[NOTE]:

collections.deque is faster than Python pure list in a loop Relevant-Post.

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
3

None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.

l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
1

New lists can be made by simply adding lists together.

list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)
Erico9001
  • 75
  • 4