0
Python lists
Why do the number 5 still appears in the output? numbers = [1, 2, 3, 8, 5, 5, 7, 5, 9] for i in numbers: if i == 5: numbers.remove(5) print(numbers)
4 ответов
+ 2
You can use a list comprehension:
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print (x)
# [1, 3, 4, 3]
+ 3
For loop in python uses an iterator which moves over the values on by one.
When you use the remove method, the iterator automatically moves the the next 5 in the list.
But afterwards, the loop jumps again to the next item (7) without getting the chance to check for the second 5.
Finally, i think you can fix it by using a while loop instead:
i=0
while i<len(numbers):
if numbers[i]==5:
numbers.remove(5)
continue
i+=1
print(*numbers)
0
Alright got it thanks all