1

I'm new to python and i can't figure out how to write a reverse for loop in python.

e.g. the python equivalent to the C lang loop

for (i = 10; i >= 0; --i) {
    printf ("%d\n", i);
}
1

4 Answers 4

11
for i in range(10, -1, -1):
    print i

You rarely need indexed loops in Python though.

Usually you're iterating over some sequence:

for element in sequence:
   do_stuff(element)

To do this in reverse:

for element in reversed(sequence):
   do_stuff(element)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use python range method.

for loop in python equavalent to C will be:

for i in range(10, -1, -1):
    print i

Comments

0

try this for i in range(10,-1,-1)

Comments

0

As Pavel mentions, you rarely need indexed loops. For those occasions you do, though, there's enumerate:

for i, element in enumerate(sequence):
    print '%s is in index %d' % (element, i)

Comments