Home Remove all occurrences of a value from a list?
Reply: 0

Remove all occurrences of a value from a list?

user484
1#
user484 Published in June 20, 2018, 7:18 am

In Python remove() will remove the first occurrence of value in a list.

How to remove all occurrences of a value from a list, without sorting the list?

This is what I have in mind.

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> def remove_values_from_list(the_list, val):
        while val in the_list:
            the_list.remove(val)
>>> remove_values_from_list(x, 2)
>>> x
[1, 3, 4, 3]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.433422 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO