I'm getting an error I don't understand, namely, 9 is not being removed from my list:
new_list = [4,6,9,8]
for j in new_list:
if j * 2 >= 10:
new_list.remove(j)
print new_list
>> [4, 9]
I'm getting an error I don't understand, namely, 9 is not being removed from my list:
new_list = [4,6,9,8]
for j in new_list:
if j * 2 >= 10:
new_list.remove(j)
print new_list
>> [4, 9]
As pointed out by @blhsing you can't mutate a list you are iterating over, as you will get unpredictable results. You can , however, use a list comprehension to construct a new list, e.g.:
old_list = [4,6,9,8]
new_list = [j for j in old_list if j*2 < 10]
You can't mutate the list you're iterating with. Use a copy of it instead:
new_list = [4,6,9,8]
for j in new_list[:]:
if j * 2 >= 10:
new_list.remove(j)
print new_list
This outputs:
[4]