[Tutor] Selecting first matching element from a list
bob gailer
bgailer at gmail.com
Mon Jan 12 18:21:53 CET 2009
Noufal Ibrahim wrote:
> Hello everyone,
> What is the pythonic way of selecting the first element of a
> list matching some condition?
> I often end up using
>
> [x for x in lst if cond(x)][0]
>
> This looks bad and raises IndexError if nothing is found which
> is ugly too.
1) itertools.dropwhile(cond, lst) will return a list with the desired
element first.
2) "looks bad" and "is ugly" are emotional responses. What are you
feeling and wanting when you say those things?
3) You can avoid the index error:
lst2 = [x for x in lst if cond(x)]
if lst2:
desired = lst2[0]
else:
deal with element not found.
OR
for x in lst:
if cond(x):
break
else:
deal with element not found.
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list