Skip to content

Instantly share code, notes, and snippets.

@shreezan123
Created February 26, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreezan123/7e1a79713fc44f4602fca3afc242b6eb to your computer and use it in GitHub Desktop.
Save shreezan123/7e1a79713fc44f4602fca3afc242b6eb to your computer and use it in GitHub Desktop.
A confusion related to index of for loop.
'''The code is meant to skip adding the character "a" and any other character that comes after "a". For this, I check if string's [i th] index = a, and add 1 to index, so that new index will be able to skip the character coming after "a". But this does not seem to be happening. Why is it so ?'''
str1 = "abcde"
str2 = ""
for i in range(len(str1)):
if str1[i] == "a":
i +=1
continue
else:
str2 += str1[i]
print (str2)
#Output is bcde. But why ?
@sushanb
Copy link

sushanb commented Feb 26, 2017

Here, i += 1 is extremely bad code because you are interfering with the Looping abstractions values.

Your code will work even if you do not write i+= 1 or write i += 100000 because after going to the for loop (after continue statement), you value (i) is incremented by the previous stored value of i (i = prev_i(0) + 1 and i == 1) eventually.

@sushanb
Copy link

sushanb commented Feb 26, 2017

str1 = "abcde" str2 = "" for i in range(len(str1)): if str1[i] == "a": continue else: str2 += str1[i] print (str2)

@sushanb
Copy link

sushanb commented Feb 26, 2017

Also, the looping variable (for) has it's own scope.

@sushanb
Copy link

sushanb commented Feb 26, 2017

When you do range(10) =
it generate a list of [0,1,2,3,4,5,6,7,8,9] (list) and value of i = list[index] and index is controlled by for loop.
That;s the main reason.

Trying range(20) in python it will generate a list

@sushanb
Copy link

sushanb commented Feb 26, 2017

str1 = "abcde"
str2 = ""
skip_bool = False
for i in range(len(str1)):
 if skip_bool == True:
     skip_bool = False
 elif str1[i] == "a":
       skip_bool = True
 else:
     str2 += str1[i]

print (str2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment