Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic python equivalent of get() for lists?

Tags:

python

idioms

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 least size of the passed in index the element is returned, otherwise None is returned?

To rephrase, what's a more idiomatic/compact version of this function:

def get(l, i):
    if i < len(l):
        return l[i]
    else:
        return None
like image 817
Scotty Allen Avatar asked Dec 27 '22 13:12

Scotty Allen


2 Answers

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
like image 167
phihag Avatar answered Jan 10 '23 23:01

phihag


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.

like image 30
unutbu Avatar answered Jan 11 '23 00:01

unutbu