'My python "for" loop is stopping after 4 times, its supposed to go through 7 loops, why is that? [duplicate]
colors= ["blue", "pink", "red", "white", "green", "orange", "black", "purple"]
colors.sort()
print (colors)
message= "we decided to remove "
for color in colors:
removed_color = colors.pop (-1)
print(message.title() + removed_color.title() + " from the list".title())
print ( ("colors remaining ".title()) + str(len(colors)).title() )
Solution 1:[1]
You are iterating from the start of the list, and removing from the end of the list, so by the time you are halfway through the list you have run out of list. Instead of using a for loop, you should instead use a while loop.
colors= ["blue", "pink", "red", "white", "green", "orange", "black", "purple"]
colors.sort()
print (colors)
message= "we decided to remove "
while colors:
removed_color = colors.pop (-1)
print(message.title() + removed_color.title() + " from the list".title())
print ( ("colors remaining ".title()) + str(len(colors)).title() )
The while colors loop will continue as long as any colors remain in the list.
Solution 2:[2]
This is happening because you're looping through the list and also mutating the list while doing that and always removing the last item on each iteration till the mutated list has reached the largest possible index with the loop count.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Turksarama |
| Solution 2 | proton |
