'Converting C style for loop to python
How do you convert a c-style for loop into python?
for (int i = m; i >= lowest; i--)
The best that I came up with was:
i = mid
for i in range(i, low,-1):
Solution 1:[1]
m from where the loop start.
l where the loop stop, and range exclude last item so l-1 and
-1 for reverse array.
for i in range(m, l-1, -1):
Solution 2:[2]
m = 20
low = 10
for i in range(m, low - 1, -1):
print i
This will count down as expected:
20
19
18
17
16
15
14
13
12
11
10
range takes three parameters, a start, a stop and the increment between each step.
Solution 3:[3]
Where possible, the Python idiom is to loop over the items directly, not to count through them. Therefore an idiomatic way to count down would be for item in reversed(list): print item or to take a reversed slice >>> someList[m:lowest-1:-1]
If you are looping over items and also need a counter, Python has enumerate() to generate counting index numbers while looping. for index, value in enumerate(someList):
It's not always possible to do this, sometimes you are counting and not going over any other data except the numbers, and range() is fine - as the other answers suggest. But when you have a for (int i=... loop, see if you can change it to act directly on the data. Writing "C in Python" is no fun for anyone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishnu Upadhyay |
| Solution 2 | Andy |
| Solution 3 | TessellatingHeckler |
