Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a Python list by predicate

Tags:

python

I would want to do something like:

>>> lst = [1, 2, 3, 4, 5] >>> lst.find(lambda x: x % 2 == 0) 2 >>> lst.findall(lambda x: x % 2 == 0) [2, 4] 

Is there anything nearing such behavior in Python's standard libraries?

I know it's very easy to roll-your-own here, but I'm looking for a more standard way.

like image 305
Eli Bendersky Avatar asked Nov 14 '08 15:11

Eli Bendersky


People also ask

How do you filter items in a list in Python?

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .

What is filter () function in Python?

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

Which function can be used to filter data using predicates?

Python filter() function Python's filter() function is used to filter the elements of an iterable (sequence) with the help of a predicate that tests each element on the iterable.

How do you filter a list?

Select a cell in the data table. On the Data tab of the Ribbon, in the Sort & Filter group, click Advanced, to open the Advanced Filter dialog box. For Action, select Filter the list, in-place.


1 Answers

You can use the filter method:

>>> lst = [1, 2, 3, 4, 5] >>> filter(lambda x: x % 2 == 0, lst) [2, 4] 

or a list comprehension:

>>> lst = [1, 2, 3, 4, 5] >>> [x for x in lst if x %2 == 0] [2, 4] 

to find a single element, you could try:

>>> next(x for x in lst if x % 2 == 0) 2 

Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension.

Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).

These raise an exception if nothing is found

filter(lambda x: x % 2 == 0, lst)[0] [x for x in lst if x %2 == 0][0] 

These return empty lists

filter(lambda x: x % 2 == 0, lst)[:1] [x for x in lst if x %2 == 0][:1] 
like image 190
John Montgomery Avatar answered Sep 18 '22 17:09

John Montgomery