6

C:

# include <stdio.h>
main()
{
    int i;
    for (i=0; i<10; i++)
    {
           if (i>5) 
           {
             i=i-1;     
             printf("%d",i);
           } 
    }
}

Python:

for i in range(10):
   if i>5: i=i-1
   print(i)

When we compile C code, it goes into a infinite loop printing 5 forever, whereas in Python it doesn't, why not?

The Python output is:

0 1 2 3 4 5 5 6 7 8

4
  • 2
    @spatz is right. If for some reason you still want to do this in python, use a while loop Commented Jan 21, 2012 at 16:07
  • 4
    The answer to your question is "Because they're different languages". They're not supposed to work alike. If they worked alike, they'd be the same language. Commented Jan 21, 2012 at 18:34
  • The reason this is the case is that in C-style code you often want the actual number i, which you use to index into some data structure or other. In higher-level code such as Python's, you don't usually want to do this; the iteration will be taken care of by the object over which you want to iterate. Commented Jan 21, 2012 at 18:55
  • Because Python and C are different languages with different semantics Commented Nov 6, 2018 at 8:09

4 Answers 4

29

In Python, the loop does not increment i, instead it assigns it values from the iterable object (in this case, list). Therefore, changing i inside the for loop does not "confuse" the loop, since in the next iteration i will simply be assigned the next value.

In the code you provided, when i is 6, it is then decremented in the loop so that it is changed to 5 and then printed. In the next iteration, Python simply sets it to the next value in the list [0,1,2,3,4,5,6,7,8,9], which is 7, and so on. The loop terminates when there are no more values to take.

Of course, the effect you get in the C loop you provided could still be achieved in Python. Since every for loop is a glorified while loop, in the sense that it could be converted like this:

for (init; condition; term) ...

Is equivalent to:

init
while(condition) {
    ...
    term
}

Then your for infinite loop could be written in Python as:

i = 0
while i < 10:
    if i > 5:
        i -= 1
    print i
    i += 1
Sign up to request clarification or add additional context in comments.

Comments

6

The two constructs are both called for loops but they really aren't the same thing.

Python's version is really a foreach loop. It runs once for each element in a collection. range(10) produces a list like [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] So the for loop runs once for each member of the collection. It doesn't use the value of i in deciding what the next element is, it always takes the next element in the list.

The c for loop gets translated into the equivalent of

int i = 0
while i < 10:
   ...
   i++;

Which is why you can manipulate the i.

Comments

4

Because your two examples are completely different things.

range(10) in python produces a list of values 0 - 9, then for i in returns each value as i. This is generally referred to as a "for-each" loop. You are operating on a value, not the iterator, when you say i=i-1 in your python example.

Comments

1

http://docs.python.org/tutorial/controlflow.html

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

a = ['cat', 'window', 'defenestrate']
for x in a:
    print x, len(x)

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

Of course the sequence generated by range is not mutable.

3 Comments

The range sequence is mutable in python 2.x
I guess if you assign the result to a list, but wouldn't it seem that in the example question it would be changing/mutating?
Your answer is fine, it just that I object to saying that the sequence generated by range is not mutable. You could mutate the object, its just that you've got no way of accessing it unless you store it as a local first.

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.