How can I do the following in Python?
array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)
I need to have the elements of an array, but from the end to the beginning.
How can I do the following in Python?
array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)
I need to have the elements of an array, but from the end to the beginning.
Possible ways,
If you want to store the elements of reversed list in some other variable, then you can use
revArray = array[::-1]
orrevArray = list(reversed(array))
.But the first variant is slightly faster:
Output:
Reversing in-place by switching references of opposite indices:
Can be done using
__reverse__
, which returns a generator.I find (contrary to some other suggestions) that
l.reverse()
is by far the fastest way to reverse a long list in Python 3 and 2. I'd be interested to know if others can replicate these timings.l[::-1]
is probably slower because it copies the list prior to reversing it. Adding thelist()
call around the iterator made byreversed(l)
must add some overhead. Of course if you want a copy of the list or an iterator then use those respective methods, but if you want to just reverse the list thenl.reverse()
seems to be the fastest way.Functions
List
Python 3.5 timings
Python 2.7 timings