Why does list have no 'get' method?

Raymond Hettinger python at rcn.com
Thu Feb 7 08:40:20 CET 2008

[Denis Bilenko]
> 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.":
 . . .
> It is often desirable, for example, when one uses the easiest
> command-line options parsing - based on absolute positions:
> With such a method instead of this (snippet from BaseHTTPServer.py)
>     if sys.argv[1:]:
>         port = int(sys.argv[1])
>     else:
>         port = 8000
> we could write
>     port = sys.argv.get(1) or 8000

At first blush that example would make it seem like a good idea, but I
don't see how the example could extend past the first index.  If the
port argument is optional, how would you know the index position of
optional arguments to follow?

With a dictionary, one could plausibly write:

  host = d.get('host', 'http://example.com')
  port = d.get('port', 8080)
  path = d.get('path', '/')

But would this make sense with a list:

  host = s.get(0, 'http://example.com')
  port = d.get(1, 8080)
  path = d.get(2, '/')

If positions 0 and 1 are optional, how do you expect to know whether
"path" is going to be at position 2?  This problem doesn't exist with
dictionaries because the presence or absence of optional entries does
not affect the key reference to other entries.  Accordingly, I
wouldn't expect that dict.get() would have a parallel list.get() with
plausible use cases.


More information about the Python-list mailing list