13steinj
13steinj

Reputation: 467

getattr for a list index in Python?

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.

Upvotes: 1

Views: 1965

Answers (1)

wim
wim

Reputation: 363456

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)

Upvotes: 6

Related Questions