Reputation:
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);
}
Upvotes: 1
Views: 183
Reputation: 3938
You can use python range method.
for loop in python
equavalent to C
will be:
for i in range(10, -1, -1):
print i
Upvotes: 1
Reputation: 599778
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)
Upvotes: 0
Reputation: 62928
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)
Upvotes: 11