简体   繁体   中英

Why is “lst.reverse()” so much faster than “lst[::-1]”?

Why is lst.reverse() so much faster than lst[::-1] ? There seems to be a large time difference in both Python 3 and 2.

Example (Python 3.5)

>>> from timeit import timeit
>>> lst = list('Crooked Hillary!') * 1000
>>> def TrumpWins(lst):
...    lst.reverse()
...    return lst
... 
>>> def SecondPlace(lst):
...   return lst[::-1]
...
>>> timeit(lambda: TrumpWins(lst), number=100000)
0.7976173080969602
>>> timeit(lambda: SecondPlace(lst), number=100000)
4.703373569995165

Jokes apart.

lst[::-1] returns a new list, while list.reverse simply performs a reversal of the list inplace . The extra overhead comes from creating a new list. And the cost/overhead will grow in proportion with the length of the list you're trying to reverse.

A fairer comparison might be to copy the list before invoking the reverse method:

In [14]: l = [1]*1000

In [15]: %%timeit
   ....: l[::-1]
   ....:
100000 loops, best of 3: 5.64 µs per loop 

In [16]: %%timeit
   ....: l[:].reverse()
   ....:
100000 loops, best of 3: 6.27 µs per loop

Nearly equal timings, with reverse losing out in this case due to the added overhead of the method call, as against the first case which uses a language construct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM