The Python Oracle

Find first sequence item that matches a criterion

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Find First Sequence Item That Matches A Criterion
00:30 Accepted Answer Score 752
01:01 Answer 2 Score 2
01:13 Thank you

--

Full question
https://stackoverflow.com/questions/9868...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 755


If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).




ANSWER 2

Score 2


This will return the object if found, else it will return "not found"

a = [100, 200, 300, 400, 500]

def search(b):
    try:
        k = a.index(b)
        return a[k] 
    except ValueError:
        return 'not found'

print(search(500))