0

How is that i get the reverse iteration using the following code. Should I be using the reduce function or something?

Example:

for i in range(4):
    print i ////0 1 2 3

how do i print the same in the reverse order

3 2 1 0

a=[5,2,1,4,3]

I also want to print the above array in reverse using the index and not a[::-1] i.e,i want to first print

 a[4] //get index starting from last how to achieve this
 a[3]
 a[2]
 a[1]
 a[0]
4
  • range(4, 0, -1) creates a reverse range. Don't understand second part of your quetion, though. Commented Feb 20, 2012 at 9:57
  • @kirilloid range(4, 0, -1) is not reversed(range(4)) Commented Feb 20, 2012 at 9:59
  • 1
    Yes, it should be range(3, -1, -1) and solution with reversed is better Commented Feb 20, 2012 at 10:04
  • For the last part of your question, maybe for i, x in reversed(list(enumerate(a))) will suit better than for i in range(len(a), -1, -1)? Commented Feb 20, 2012 at 10:10

6 Answers 6

5

Use the reversed function:

for i in reversed(range(4)):
    print i

prints:

3
2
1
0

and

a=[5,2,1,4,3]
for i in reversed(a):
    print i

prints

3
4
1
2
5
Sign up to request clarification or add additional context in comments.

Comments

1

One approach involves reversing a list before iterating over it. Though this technique wastes computer cycles, memory, and lines of code:

rseqn = list(seqn)
rseqn.reverse()
for value in rseqn:
    print value

Comments

0

This works:

range(4, -1, -1)
// [4, 3, 2, 1, 0]

Comments

0
>>> for i in reversed(range(4)):
...   print(i)
...
3
2
1
0

Comments

0

len() returns the length of a list. So you can use len(a)-1 to get the last index of list a .

Comments

0

You can use the reverse function of a list.

>>> a = [1,2,3,4]
>>> a.reverse()
>>> a
[4, 3, 2, 1]

Use the answer of eumiro for a one time reverse (i.e. if you only need it once). Otherwise use my approach because the conversion is done on the list itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.