I'd say the most closely related solution would be to use next
instead of any
:
>>> next((s for s in l if s.startswith(wanted)), 'mydefault')
'threes'
>>> next((s for s in l if s.startswith('blarg')), 'mydefault')
'mydefault'
Just like any
, it stops the search as soon as it found a match, and only takes O(1) space. Unlike the list comprehension solutions, which always process the whole list and take O(n) space.
Ooh, alternatively just use any
as is but remember the last checked element:
>>> if any((match := s).startswith(wanted) for s in l):
print(match)
threes
>>> if any((match := s).startswith('blarg') for s in l):
print(match)
>>>
Another variation, only assign the matching element:
>>> if any(s.startswith(wanted) and (match := s) for s in l):
print(match)
threes
(Might want to include something like or True
if a matching s
could be the empty string.)