2

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):

4 Answers 4

7
for i in range(m, low - 1, -1):

Keep in mind range is exclusive of the stop parameter.

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

The difference between this code and the C code is that in Python 2, a list is being constructed in memory by range so for very huge ranges this could be a problem. Replacing range with xrange would not build a list in memory and make the code practically the same. In Python 3 this issue no longer exists.

Sign up to request clarification or add additional context in comments.

Comments

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):

Comments

1
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.

Comments

1

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.

Comments

Your Answer

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