12

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.

alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

4

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.

Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
  • `list(reverse(x))` is somewhere between method #1 and #3. – simonzack Sep 22 '14 at 12:50
  • it's `list(reversed(x))` I add it to the answer. – Jérôme Radix Sep 22 '14 at 13:00
  • FYI, on my machine with python3 at least, deque is slightly faster than append and reverse (510nsec vs 674nsec). This answer short-circuits the append and reverse option (by doing a reversed copy, which is NOT the same thing in the general sense), and so does not give any timings for that scenario. – ibrewster Apr 27 '20 at 22:18