0
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() )
Kraigolas
  • 5,121
  • 3
  • 12
  • 37
Desire
  • 1
  • 2

2 Answers2

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