Sayed Hossain Sayed Hossain - 14 days ago 7
Python Question

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?? Please answer and pardon me if it has already been asked before and is a silly one... Thanks in advance... :D

Answer

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