Slice equivalent to dict.get

Ian Kelly ian.g.kelly at gmail.com
Thu Mar 31 11:43:50 EDT 2016


On Thu, Mar 31, 2016 at 9:24 AM, Peter Otten <__peter__ at web.de> wrote:
> But note:
>
>>>> def get(seq, index, default=None):
> ...     return (seq[index:index+1] or [default])[0]
> ...
>>>> get("abc", -1, "default")
> 'default'

The discontinuity between -1 and 0 in indexing is a pain in the rear.
Negative indexes are one of those things that may seem like a good
idea at first, but I think in the end it causes more trouble than it's
worth. There's nothing you can do with L[-x] that you can't do more
explicitly with L[len(L) - x].



More information about the Python-list mailing list