[Python-ideas] list.index() extension
denis.spir at free.fr
Sun Apr 5 10:01:49 CEST 2009
Le Sun, 5 Apr 2009 00:39:24 +0000 (UTC),
Benjamin Peterson <benjamin at python.org> s'exprima ainsi:
> 2009/4/4 Leif Walsh <leif.walsh at gmail.com>:
> > Maybe you didn't understand what I meant. Try the following code,
> > with your favorite list and object. I promise it works.
> > try:
> > print "The index of the first element that 'is obj' is %d." % (idx
> > for idx, elt in enumerate(lst) if elt is obj).next()
> > except StopIteration:
> > print "obj is not in lst"
> Yes, I saw that but it still strikes me as much uglier than necessary.
An issue is imo that (idx for idx, elt in enumerate(lst) if elt is obj) builds a generator able to yield every indexes of elements that satisfy the condition; while all you want is the first one (as expressed by ".next()").
On one hand, I have very few use cases for such a "conditional find". One the other hand, it's simple, practicle and consistent. Adding an optional parameter, with '==' as default, as originally proposed by Benjamin, does not harm in the common case and does not break any exiting code.
In case it would be accepted, then rather in builtin find and count methods for I see this as a semantic extension, not a fully different feature.
la vita e estrany
More information about the Python-ideas