How to remove all elements from a list equal to a certain value

Asked

Viewed 87 times

1

How to remove all values from a list that will have the same meaning for example:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim3', 'sim4']

Is there any way to make a looping loop as long as there are values with 'yes', something like array.remove('sim'), or there is a method to it?

2 answers

5


Don’t do like the another answer (which has been deleted), because removing elements from a list in the same loop that iterates on it does not work in all cases. Ex:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim', 'sim3', 'sim4'] 
 
for i in array:
    array.remove('sim')
print(array) # ['sim2', 'sim', 'sim3', 'sim4']

Note that not all "yes" have been removed. This behavior is best explained here and here.

Finally, the documentation cites two solutions to avoid this problem. Or you create another list with only the values you want:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim', 'sim3', 'sim4'] 
 
outra = []
for x in array:
    if x != 'sim':
         outra.append(x)

print(outra)

Or you iterate over a copy of the list:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim', 'sim3', 'sim4'] 

for x in array.copy():
    if x == 'sim':
        array.remove(x)

print(array)

The first option above can also be done with comprehensilist on, much more succinct and pythonic:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim', 'sim3', 'sim4'] 
 
outra = [ x for x in array if x != 'sim' ]
print(outra)
  • 2

    Could add that naughty solution with list comprehession to stay top xD

  • 2

    I blacked out because as you said was wrong, I’ll give a study and try to remake the correct way, thanks for the observation :)

  • 1

    @Woss I was going to put but I forgot. It’s there, thank you! :-)

2

Another alternative to what @Senior Code said is to use a while rather than a for loop, since we may come across lists of which we don’t know how many yes will be on the list the code looks like this:

array = ['sim', 'sim', 'sim', 'sim', 'sim2', 'sim3', 'sim4']

while 'sim' in array:
    array.remove('sim')

print(array)

['sim2', 'sim3', 'sim4']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.