Which is faster and more pythonic?
- reverse an appended list
- start prepending the list from the start
- using
deque
E.g. here's ome made-up data to store into a new list
# Let's say my function outputs these output individually.
x = [12,34,44,346,345,876,123]
Reversing an appended list:
new_list = []
for i in x:
new_list.append(i)
new_list = newlist[::-1]
Prepending to the list:
new_list = []
for i in x:
new_list.insert(0,i)
Using deque:
from collections import deque
for i in x:
x.appendleft(i)
Please note that my question is not how to reverse list. Please also assume that the list is of size ~20,000.
timeit
and see? – Pudensdeque
? – Simpfor
loop, you could directly usenew_list = x[::-1]
, ornew_list = list(x)[::-1]
ifx
isn't a list, or loop overreversed(list(x))
if you don't actually need a list out of this. – Fletatimeit
but it's quite similar... – Fredenburglist(reversed(x))
would be the fastest – Aglitter1.69 ms
second128 ms
list(reversed)
129 µs
on 20k element list – Aglitterreversed
on arbitrary iterables, though. – Fletalist(reversed(x))
returns a reversed list – Aglitterx
is a generator. You can't callreversed
on that. – Fletax[::-1]
outperformslist(reversed(x))
. – Fletadeque
is going to be much faster than either of the alternatives; O(1) appendleft operations are pretty much the entire point of it existing... Of course, you don't say what you plan to do with this data structure after you build it. If accessing arbitrary elements by index is one of the things you want to be able to do easily, you'll lose the efficiency you got in building the thing while using it. – Simp