+ 1
Removing a value(multiple occurrence) from list
a list has a value which is repeated 3 times. But when i applied remove function for the value which is repeated multiple times , only the first occurrence is removed. Please explain? ex: nums=[1,2,3,2,4,5,2] nums.remove(2) print(nums)
2 odpowiedzi
0
This function remove a single element from the list .But you can use a for loop to iterate throw all elements and remove the number 2 in each iteration
for i in nums:
nums.remove(2)
print(nums).
Or you can use filter method with lambda function
print(list(filter(lambda x: x != 2,nums)))
0
remove function removes element at first occurrence only.. If you want remove more, use a loop then by condition count(2)>1 then remove else not..
In other way, you can use set method which removes dublicates so you can do like this list(set(nums)) this forms a set again back to a list of no more dublicates..
You can use pop(at_index) remove element at specified index..
Hope it helps..