Why does list have no 'get' method?

Tim Golden mail at timgolden.me.uk
Thu Feb 7 10:06:32 CET 2008

Denis Bilenko wrote:
> Why does list have no 'get' method with exactly the same semantics as
> dict's get,
> that is "return an element if there is one, but do NOT raise
> an exception if there is not.":
>     def get(self, item, default = None):
>         try:
>             return self[item]
>         except IndexError:
>             return default
> It is often desirable, for example, when one uses the easiest
> command-line options parsing - based on absolute positions:

Dodging your question slightly (and at the risk of teaching
my grandmother to suck eggs) I sometimes use this idiom for
checking params. Obviously it only goes so far, but it's
fairly compact:

<Noddy example code>
import os, sys

if __name__ == '__main__':
   ARGS = None, "DEV"
   filename, db = \
     (j or i for i, j in map (None, ARGS, sys.argv[1:]))

   print sys.argv
   print filename, db



More information about the Python-list mailing list