Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it cheaper to reverse an appended list or to prepend a list? - python

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.

like image 432
alvas Avatar asked Aug 09 '14 20:08

alvas


People also ask

What is the easiest way to reverse a list in Python?

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.

What is the difference between append () and extend () methods of list?

append() adds a single element to the end of the list while . extend() can add multiple individual elements to the end of the list.

Is extend faster than append?

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 appending a list and extending 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.


1 Answers

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.

like image 129
Jérôme Radix Avatar answered Oct 21 '22 13:10

Jérôme Radix