Python Forum
unable to remove all elements from list based on a condition - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: unable to remove all elements from list based on a condition (/thread-41502.html)



unable to remove all elements from list based on a condition - sg_python - Jan-27-2024

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 ?


RE: unable to remove all elements from list based on a condition - Yoriz - Jan-27-2024

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


RE: unable to remove all elements from list based on a condition - Pedroski55 - Jan-27-2024

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.


RE: unable to remove all elements from list based on a condition - deanhystad - Jan-27-2024

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])