-2

I'm looking for a more pythonic way to construct this check:

good_result = None
for item in items:
    result = process(item)
    if result.isGood():
        good_result = result
        break
if not good_result:
    deal_with_consequences_of_bad_result()

Assume that we don't want to process all items in the list, so I only want to check for the the first occurrence of a good result.

0

1 Answer 1

1

Maybe something like this:

good_result = next((result for item in items if (result := process(item)).isGood()), None)

if not good_result:
    deal_with_consequences_of_bad_result()
Sign up to request clarification or add additional context in comments.

2 Comments

I'd say the for/else approach is more readable. Also if not good_result will not work well for good_result = 0.
@Jeyekomon I agree that for/else approach is more readable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.