Python Forum

Full Version: unable to remove all elements from list based on a condition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
list=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]

for a in list:
    if a<=6.0:
       list.remove(a)
      
print(list)
The output i am getting is :
Output:
[6.2, 4.8, 6.1, 6.1, 6.5, 5.8, 6.2]
Q> Why 5.8 is NOT getting removed ?
Removing an item from the list while looping over it changes the index location of the remaining items.
You can loop over a copy of the list and remove items from the original list

values=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]
 
for value in values[:]:
    if value<=6.0:
       values.remove(value)
       
print(values)
Output:
[6.2, 6.1, 6.1, 6.5, 6.2]
Also note that you shouldn't use list as the variable name to contain your list as it overwrites the keyword list
As Yoriz said, it is not good to remove items from a list while you are looping through it. Will cause problems!

Nor is it good to use the reserved word list as you did.

You could approach this from the other way round, instead of slicing out a copy, create a new list to start with and append:

mylist=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]
mynewlist = [] 
for a in mylist:
    if a>=6.0:
       mynewlist.append(a)
print(mynewlist)
Output:
[6.2, 6.1, 6.1, 6.5, 6.2]
I think it is a good idea to preserve the original list for later use perhaps.
A list comprehension would work well here
values = [6.2, 5.9, 4.8, 6.1, 6.1, 6.5, 5.9, 5.8, 6.2]
print([value for value in values if value > 6])