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

无人久伴 提交于 2019-12-10 15:55:32

问题


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

回答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



回答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.



来源:https://stackoverflow.com/questions/7699937/whats-the-idiomatic-python-equivalent-of-get-for-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!