Neel Kamath Neel Kamath - 6 months ago 11
Python Question

Python: Why does my "variable += 1" not work as expected?

username = "neelkamath@gmail.com"
usernamelist = []
next = 0
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
next += 1
username = username[next:]
print(usernamelist)


I'm trying to output every part of the username (like "n", "ne", "nee", ... , "neelkamath@gmail.com", "e", "ee", ... , "eelkamath@gmail.com" etc.) but instead of going from "n" to "neelkamath@gmail.com" and then from "e" to "eelkamath@gmail.com" and then from "e" to "elkamath@gmail.com"; it skips an extra one letter each time, despite me only adding 1 to "next". It goes from "n" to "e" (one letter ahead, as it's supposed to) to "l" (2 letters ahead) to "m" (3 letters ahead) and so on. Am I placing the
next += 1

in an incorrect position?

Answer

You don't need to increment next if you want to remove one character for each iteration of the while loop:

username = "neelkamath@gmail.com"
usernamelist = []
while len(username) > 0:
    for part in accumulate(username):
        usernamelist.append(part)
    username = username[1:]
print(usernamelist)

By incrementing next you increment the number of characters to be skipped:

At first iteration: after username = username[1:] username is "eelkamath@gmail.com"

At second iteration: after username = username[1:] username is "elkamath@gmail.com" but after username = username[2:] username is "lkamath@gmail.com"

Comments