is there such a built-in funciton, similar to filter

W

wcc

Hello,

Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2,
5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to
find the first item in the list that returns Ture when applying the
filter function. In this case, I only want to get the 5, and its index
2. Is there a built-in function, or function from a module for that?
I think it is not hard to write a function for this. But knowing
Python is "battery included", I thought I'd like to ask. Thanks for
your help.

- wcc
 
M

Michael Hoffman

wcc said:
Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2,
5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to
find the first item in the list that returns Ture when applying the
filter function. In this case, I only want to get the 5, and its index
2. Is there a built-in function, or function from a module for that?
I think it is not hard to write a function for this. But knowing
Python is "battery included", I thought I'd like to ask. Thanks for
your help.

You can use a generator expression like this:
>>> items = [1, 2, 5, -3, 4, 8]
>>> ((index, item) for index, item in enumerate(items) if item > 3).next()
(2, 5)
 
T

Terry Reedy

Michael Hoffman said:
wcc said:
Beginner learning Python here. I know filter(lambda x: x > 3, [1, 2,
5, -3, 4, 8]) will give me a list [5, 4, 8]. What if I only need to
find the first item in the list that returns Ture when applying the
filter function. In this case, I only want to get the 5, and its index

You have made two important changes to the function return value.
Filter returns a list of items. You want an item and index.
What if there is no first item?

A 'battery' is something like the email, html, xml modules that assist
major application areas. Not every easily written 3-line function ;-)
You can use a generator expression like this:
items = [1, 2, 5, -3, 4, 8]
((index, item) for index, item in enumerate(items) if item >
3).next()
(2, 5)
items = [0,1,2,3]
((index, item) for index, item in enumerate(items) if item > 3).next()

Traceback (most recent call last):
File "<pyshell#82>", line 1, in -toplevel-
((index, item) for index, item in enumerate(items) if item > 3).next()
StopIteration

I believe ifilter from the itertools module will act the same.

Terry Jan Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,019
Latest member
RoxannaSta

Latest Threads

Top