Sayed Hossain
Sayed Hossain

Reputation: 23

This python for loop and if statement are acting strange

I was solving a problem where I needed to write a code like following:

c = [0,0,1,0,0,1,0]
for i in range(7):
    if(i<7-2 and c[i+2] == 0):
        i += 1
    print(i)

I expected output like this:

0
2
3
5
6

But I am getting this:

0
2
3
3
5
5
6

But with same logic/code in C it is working fine...

#include<stdio.h>
int main(){
    int c[] = {0,0,1,0,0,1,0};
    int i;
    for(i=0;i<7;i++){
        if(i<7-2 && c[i+2] == 0){
            i++;
        }
        printf("%d\n",i);
    }
}

What is the reason(s) or what am I missing here?

Upvotes: 2

Views: 182

Answers (2)

Mureinik
Mureinik

Reputation: 311143

The for-in loop just assigns every member of the range to i in it's turn, it does not increment i. Thus, any modification you make to i is lost at the end of the loop's current iteration.

You can get the desired behavior with a while loop, but you'd have to increment i yourself:

i = 0
while i < 7:
    if(i<7-2 and c[i+2] == 0):
        i += 1
    print(i)
    i += 1

Upvotes: 1

Drathier
Drathier

Reputation: 14519

A for i in range(7) loop in python behaves as for i in [0,1,2,3,4,5,6]. i is the values in that list, rather than an index being incremented. Thus, your i += 1 doesn't do what you think it does.

You could use a while loop to get the same behavior as the c for loop, but there's probably a more pythonic way to write it.

i = 0
while i < 7:
   if(i<7-2 and c[i+2] == 0):
        i += 1
   print(i)
   i+=1

Upvotes: 2

Related Questions