Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a quick way to delete all elements from a list that do not satisfy a constraint?

Tags:

python

I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0?

like image 697
mopy Avatar asked Oct 09 '10 02:10

mopy


People also ask

Which method is used to remove all elements of the list?

Java List remove() method is used to remove elements from the list.

Which method is used to delete elements from a list if index is not known?

The method pop() can be used to remove and return the last value from the list or the given index value. If the index is not given, then the last element is popped out and removed.

How do you remove all elements in a list that are a certain value Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do I delete or remove elements from a list?

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method.


1 Answers

[x for x in lst if fn(x) != 0]

This is a "list comprehension", one of Python's nicest pieces of syntactical sugar that often takes lines of code in other languages and additional variable declarations, etc.

See: http://docs.python.org/tutorial/datastructures.html#list-comprehensions

like image 121
dkamins Avatar answered Sep 22 '22 12:09

dkamins