3

I am very new to python.I had a small query about for loop in c++ and python.In c,c++ if we modify the variable i as shown in below example ,that new value of i reflects in the next iteration but this is not the case in for loop in python.So ,how to deal with it in python when it is really required to skip some iterations without actually using functions like continue ,etc.

for loop in c++

for(int i=0;i<5;++i)
{   
   if(i==2)
    i=i+2;

   cout<<i<<endl;
}

Output

0

1

4

for loop in python

for i in range(5):
     if i==2:
        i=i+2
     print i

Output

0

1

4

3

4
1
  • 1
    In Python, use while to do such things. Commented Feb 1, 2013 at 21:30

5 Answers 5

6

I'd in general advice against modifying the iteration variable in C++, as it makes the code hard to follow.

In python, if you know beforehand which values you want to iterate through (and there is not too many of them!) you can just build a list of those.

for i in [0,1,4]:
    print i

Of course, if you really must change the iteration variable in Python you can just use a while loop instead.

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

Comments

4

This is because in python, at each iteration of the loop, the variable i is chosen as the next element in range(5). But, in c++, the variable i is managed by both the loop increment, and the stuff that happens inside the loop.

Comments

1

The i variable is being set at every iteration of the loop to the output of the range(5) iterator. Although you can modify in the loop, it gets overwritten.

Comments

1

i is reset each iteration, meaning any mutation to i is ignored the next loop around. As Daniel Fischer said in a comment, if you want to do this in Python, use a while loop.

It's like:

for (int i = 0; i < 5; ++i) {
    int x = i;
    if (x == 2) {
        x = x + 2;
    }
    std::cout << x << std::endl;
}

Comments

0

this is because range(5) is [0,1,2,3,4], for i in range(5) is therefore for i in [0,1,2,3,4]

Comments

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.