next((x for x in test_list if x.value == value), None)
This gets the first item from the list that matches the condition, and returns None
if no item matches. It's my preferred single-expression form.
However,
for x in test_list:
if x.value == value:
print("i found it!")
break
The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:
for x in test_list:
if x.value == value:
print("i found it!")
break
else:
x = None
This will assign None
to x
if you don't break
out of the loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…