How can i do this 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 this 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.
>>> L = [0,10,20,40]
>>> L[::-1]
[40, 20, 10, 0]
Extended slice syntax is explained well here: http://docs.python.org/release/2.3.5/whatsnew/section-slices.html
By special request in a comment this is the most current slice documentation.
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]
Or
>>> L[::-1]
[40, 20, 10, 0]
If you just use the array once (and can discard it), the most idiomatic solution is:
array = [0,10,20,40]
while array:
item = array.pop()
The most direct translation of your requirement into Python is this for
statement:
for i in xrange(len(array) - 1, -1, -1):
print i, array[i]
This is rather cryptic but may be useful.