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 handles a as integer, thus I cannot use append, or extend either.
How would you do this?
-
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:15
10 Answers
>>>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.
- 19,655
- 7
- 34
- 59
-
23The 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
-
8The question clearly states a _new_ list should be created. So this might be fast — but wrong. ;-) – BlackJack Oct 18 '16 at 16:04
-
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. – Nullify Oct 19 '16 at 08:19
-
1Whatever he describes may be exactly what he needs. How do you know it is not necessary to work with a copy instead of changing the original list? It could be an argument to a function for instance and the caller doesn't expect the list to be modified and it would introduce an error into the program to do so. – BlackJack Oct 19 '16 at 12:50
-
1In 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. :) – Nullify Oct 19 '16 at 13:00
-
I hear by boost this answer to have more points than the selected one. – EMiller May 18 '19 at 01:57
-
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
-
-
@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
>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li # Don't use 'list' as variable name.
[5, 1, 2, 3]
- 203,151
- 43
- 392
- 509
-
392I 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
-
96@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
-
6It 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
-
21@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
-
1@Marcel Pfeiffer `collections.deque.appendleft()` should be even faster for large len(li). – cowbert Sep 13 '17 at 17:55
-
-
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
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
- 73,231
- 20
- 109
- 138
-
6Sometimes 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
-
1in 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
Another way of doing the same,
list[0:0] = [a]
- 1,406
- 9
- 14
-
31You don't need the first 0. The colon already say that's before the start -- my_list[:0]=[a] does it. – Stefan Gruenwald Sep 14 '14 at 13:39
-
-
4This is interesting to know about, but I would avoid this because I think it might cause confusion. – xjcl Feb 05 '19 at 20:06
-
1This is not elegant, it's unnecessarily confusing and difficult to read. – pigi5 Nov 23 '21 at 07:14
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).
- 149
- 1
- 5
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)
- 144
- 1
- 6
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.
- 21,522
- 19
- 109
- 128
New lists can be made by simply adding lists together.
list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)
- 79
- 4
-
3This is already covered by the top rated answer. Please explain how this adds new information to the issue. – Mike Scotty Apr 12 '18 at 07:56
-
4
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()
- 19,499
- 9
- 39
- 60
- 29
- 1