Why does list have no 'get' method?

Denis Bilenko denis.bilenko at gmail.com
Thu Feb 7 00:31:36 EST 2008


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:

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

which is both more condense and more clear.

The change is unlikely to break anyone's code.
(nobody uses getattr(obj, 'get') to distinguish between lists and dicts, right?)



More information about the Python-list mailing list