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

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to