Reputation: 1142
coins=[100,50, 20, 10, 5, 2, 1]
n=10
for el in coins:
if el>n:
coins.remove(el)
print coins
The program above is supposed to remove all the elements in list coins which are greater than 10 The desired output is
[10, 5, 2, 1]
but i am getting
[50, 10, 5, 2, 1]
What is going wrong...
Upvotes: 0
Views: 46
Reputation: 4855
You can also do it with a while loop
while i < len(coins):
if coins[i] > n:
coins.pop(0)
else:
i+=1
Upvotes: 0
Reputation: 129497
You shouldn't alter a list while iterating over it. Try using a list comprehension instead:
coins = [el for el in coins if el <= n]
The reason you shouldn't remove elements while iterating is because it can result in other elements being skipped. For example, imagine that we want to remove b
from the list [a, b, c, d]
:
----------------- | a | b | c | d | ----------------- ^ (we're on b) ----------------- | a | | c | d | ----------------- ^ (remove b) ------------- | a | c | d | ------------- ^ (shift elements of list down to fill vacancy) ------------- | a | c | d | ------------- ^ (step)
Notice that we skipped c
.
Upvotes: 4