0

I know I can do a try/except or if/else and set a default based on the error or else clause, but I was just wondering if there was a one liner that could do it like getattr can.

13steinj
  • 427
  • 2
  • 9
  • 16
  • a related question: http://stackoverflow.com/questions/5125619/why-list-doesnt-have-safe-get-method-like-dictionary – newtover Nov 21 '15 at 21:47

1 Answers1

6

The good: just def a helper function

def my_getitem(container, i, default=None):
    try:
        return container[i]
    except IndexError:
        return default

The bad: you can one-liner the conditional version

item = container[i] if i < len(container) else default

The ugly: these are hacks, don't use.

item = (container[i:] + [default])[0]

item, = container[i:i+1] or [default]

item = container[i] if container[i:] else default

item = dict(enumerate(container)).get(i, default)

item = next(iter(container[i:i+1]), default)
wim
  • 338,267
  • 99
  • 616
  • 750