How do I find an object in a sequence satisfying a particular criterion?
List comprehension and filter go through the entire list. Is the only alternative a handmade loop?
mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # Returns 20
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s the pattern I use:
Or, in Python 2.4/2.5,
next()is a not a builtin:Do note that
next()raisesStopIterationif no element was found. In most cases, that’s probably good. You asked for the first element, no such element exists, and so the program probably cannot continue.If, on the other hand, you do know what to do in that case, you can supply a default to
next():