Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does passing reverse=True when sorting a list in Python affect efficiency?

When calling sort() on a list in Python, passing cmp=f slows down the sort. Does passing reverse=True affect the efficiency of the sort in any way (or is it identical to sorting without reversing)?

like image 705
jrdioko Avatar asked Jan 30 '12 19:01

jrdioko


People also ask

How do you sort a list in Python efficiently?

Sorting Basics You can also use the list.sort() method. It modifies the list in-place (and returns None to avoid confusion). Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient. Another difference is that the list.sort() method is only defined for lists.

What does reverse true mean in Python?

Setting reverse = True sorts the list in the descending order.

Which sorting technique is faster in Python?

True to its name, Quicksort is very fast. Although its worst-case scenario is theoretically O(n2), in practice, a good implementation of Quicksort beats most other sorting implementations. Also, just like merge sort, Quicksort is straightforward to parallelize.

When you use sort () it permanently changes the list?

Thus sort() method is used to arrange a list in either Ascending or Descending order. One more important thing to remember here is that sort() method changes the order of the list permanently. If you want to change the order of the list temporarily, then you need to use sorted() function.


1 Answers

From my benchmarks, there appears to be a small difference:

import timeit

setup = """
import random
random.seed(1)
l = range(10000)
random.shuffle(l)
"""

run1 = """
sorted(l)
"""

run2 = """
sorted(l, reverse=True)
"""

n1 = timeit.timeit(run1, setup, number=10000)
n2 = timeit.timeit(run2, setup, number=10000)

print n1, n2
print (n2/n1 - 1)*100,"%"

Results in (on my machine):

38.8531708717 41.2889549732
6.26920286513 %

The same run, but for a list of 1000 elements:

2.80148005486 2.74061703682
-2.17253083528 %

# ...another round...
2.90553498268 2.86594104767
-1.36270722083 %
like image 57
GaretJax Avatar answered Sep 22 '22 05:09

GaretJax