views:

218

answers:

8

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.

A: 

You just need to think backwards.

for (i=array.length(); i>0; i--)
Twitch
That's fantastic Python code you've got there! +1 for the joke on "thinking backwards" to a question about being reversed!
André Caron
And have you ever seen any Python code?
raceCh-
I'll revoke my downvote if Twitch can name *any* language where that code is correct.
Matthew Flaschen
I wasn't attempting to be coding-correct, I was giving the opposite of the code he had given before the edit. Don't downvote based on the current code he has at the top.
Twitch
+10  A: 
>>> 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.

Adam Bernier
Out of curiosity, what benefits (if any) does this have over list.reverse()?
Tim
It works for any interable, not just lists. Disadvantage is that it's not in place.
Swiss
@Tim it returns a slice, so doesn't change the actual list contents
fortran
the reversed() container is more clear.
lunixbochs
@Swiss Not in every iterable, for example, `set` is iterable, but not subscriptable.
fortran
@Swiss, Fortran - Ahh Ofcourse... Fantastic.
Tim
@lunixbochs reversed returns an iterator and not a list in Python 3.
Swiss
What's with the link to a super-old version of the Python doc?
Swiss
@Swiss right, but the OP's example was an iteration :)
lunixbochs
@Swiss Python 2.3 allowed `list`, `tuple` and `str` to utilize the extended slice syntax.
Tim McNamara
+3  A: 
for x in array[::-1]:
    do stuff
Swiss
+10  A: 

You can make use of the reversed function for this as:

>>> array=[0,10,20,40]
>>> for i in reversed(array):
...     print i
codaddict
+3  A: 
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

Or

>>> L[::-1]
[40, 20, 10, 0]
ghostdog74
+1  A: 
array=[0,10,20,40]
for e in reversed(array):
  print e
動靜能量
A: 

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()
Kimvais
Why the downvotes?
Kimvais
I didn't downvote, but I wonder if you mean that the OP should stick code in the `while` loop after the assignment to `item`? I would say that using `reversed` is both more idiomatic and more efficient.
intuited
I meant using a `while` loop instead of a `for` loop, but yeah, I guess `reversed()` is more idiomatic IF you have to keep the original data.
Kimvais
A: 

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.

John Machin