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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With