Created
February 26, 2017 21:17
-
-
Save shreezan123/7e1a79713fc44f4602fca3afc242b6eb to your computer and use it in GitHub Desktop.
A confusion related to index of for loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''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 ? |
str1 = "abcde" str2 = "" for i in range(len(str1)): if str1[i] == "a": continue else: str2 += str1[i] print (str2)
Also, the looping variable (for) has it's own scope.
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
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
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.