Is it cheaper to flip the attached list or add a list? - python
Which is faster and more pythonic?
- cancel added list
- start adding a list from the very beginning
- through
deque
eg. here ome ready data to store in a new list
# Let say my function outputs these output individually.
x = [12,34,44,346,345,876,123]
Change of attached list:
new_list = [] for i in x: new_list.append(i) new_list = newlist[::-1]
Providing a 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 a reverse listing. Also assume that this list is ~ 20,000 in size.
+3
source to share
1 answer
Your first method can be simplified to one line:
new_list = x[::-1]
Then, to check which method is faster than any other, just use timeit
(tested with python 2.7.8):
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]" "new_list = x[::-1]"
1000000 loops, best of 3: 0.215 usec per loop
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]; new_list = []" "for i in x:" " new_list.insert(0,i)"
10000 loops, best of 3: 146 usec per loop
C:\>python -m timeit -s "from collections import deque; x = [12,34,44,346,345,876,123]; new_list = deque()" "for i in x:" " new_list.appendleft(i)"
1000000 loops, best of 3: 0.713 usec per loop
C:\>python -m timeit -s "x = [12,34,44,346,345,876,123]" "new_list = list(reversed(x))"
1000000 loops, best of 3: 0.837 usec per loop
So, new_list = x[::-1]
better than any other.
You should also ask yourself if you want to "link" or "copy" items into the new list structure.
+1
source to share