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.
You can use
reversed()
Strictly speaking, the question is not how to return a list in reverse but rather how to reverse a list with an example list name
array
.To reverse a list named
"array"
usearray.reverse()
.The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using
array = array[::-1]
.For reversing the same list use:
To assign reversed list into some other list use:
Using reversed(array) would be the likely best route.
Should you need to understand how could implement this without using the built in
reversed
.This should take O(N) time.
Or