Which is faster and more pythonic?
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.
Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.
append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.
Adding Multiple Elements: append() vs extend() As you can see, appending took ~5 times longer than extending. So performance-wise, use the extend() method when adding multiple elements to a list.
What is the difference between the list methods append and extend? append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list.
Your first method could 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]
is better than any other way.
You also have to ask yourself if you want to "reference" or "copy" elements into the new list structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With