0

I am looking for a possible equivalent of the following loop in python list comprehension.

    for foo in foos:
        if foo.text == expected_text
            return foo
    return []

Something like this.

found_foo = [foo for foo in foos if foo.text == expected_text]

If this possible using list comprehension?

3
  • 2
    You return either a single foo or an empty list? This is not usually a good design Commented Aug 2, 2015 at 8:56
  • I am confused how to skip / terminate the loop when the foo_found is mathced. Commented Aug 2, 2015 at 8:58
  • Yeah found_foo is actually a list with length == 1 and when the match is not found [] with length is returned Commented Aug 2, 2015 at 8:59

1 Answer 1

5

You can use generator expression and next:

return next((foo for foo in foos if foo.text == expected_text), None)

Next will return the first yielded item that meet the condition.

In case of no matched item, next will return the default value None.

Sign up to request clarification or add additional context in comments.

1 Comment

yes. It avoids running along the whole iterable if the element is found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.