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() )
Asked
Active
Viewed 175 times
0
-
1You're mutating `colors` during the for loop by calling `pop`, which is causing the problem. – Kraigolas Jan 26 '22 at 23:40
-
Thank you so much guys!!! – Desire Jan 26 '22 at 23:42
2 Answers
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.

Turksarama
- 1,136
- 6
- 13
0
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.

proton
- 1,639
- 6
- 18
- 30