Skip to content Skip to sidebar Skip to footer

What's The Idiomatic Python Equivalent Of Get() For Lists?

Calling get(key) on a dictionary will return None by default if the key isn't present in a dictionary. What is the idiomatic equivalent for a list, such that if a list is of at le

Solution 1:

Your implementation is Look Before You Leap-style. It's pythonic to execute the code and catch errors instead:

def get(l, i, d=None):
    try:
        return l[i]
    except IndexError:
        return d

Solution 2:

If you expect l[i] to often not exist, then use:

def get(l,i):
    return l[i] if i<len(l) else None

If you expect l[i] will almost always exist, then use try...except:

def get(l,i):
    try:
        return l[i] 
    except IndexError:
        return None

Rationale: try...except is expensive when the exception is raised, but fairly quick otherwise.


Post a Comment for "What's The Idiomatic Python Equivalent Of Get() For Lists?"