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 Answers
+ 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]
+ 5
Not everything can be done using a for-loop, sometimes, you're not sure of "How many times" the loop should run, it's always adviced to use the "While" loop instead.
while 5 in numbers:
for i in numbers:
if i==5:
numbers.remove(i)
+ 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
Hot today
I have made a calculator in which my % (Percentage) not work correctly for 100%50 or 100%20.
2 Votes
Python palindrome challenge.
1 Votes
Java
0 Votes
Number of Ones ( C++ ) question!
1 Votes