list index()

BJörn Lindqvist bjourne at gmail.com
Fri Aug 31 10:19:53 EDT 2007


On 8/30/07, Carsten Haese <carsten at uniqsys.com> wrote:
> Is the Pythonic way
>
> try:
>     i = somelist.index(thing)
>     # Do something with i
> except IndexError:
>     # Do something if thing not found

That is not the Pythonic way. "# Do something with i" might also raise
an IndexError and they you are screwed. The Pythonic way is something
like:

try:
    i = somelist.index(thing)
except IndexError:
    print "Oh noes!"
else:
    # Do the thing with i

And for many cases this actually is worse/less readable than the
alternative would have been if list.index() returned -1.


-- 
mvh Björn



More information about the Python-list mailing list