Skip to main content
 首页 » 编程设计

python之如何检查列表索引是否存在

2025年05月04日11emanlee

我有以下列表

a = ['a','c','d'] 

我需要检查列表索引 4(或任何索引)是否存在于列表中。有没有类似php isset的方法在 python 中为此(不使用异常处理)?

请您参考如下方法:

if len(a) > 4: 
    # list contains fourth element, a[4] 

或

try: 
    a[4] # do something with a[4] 
except IndexError: 
    print "there is no element a[4]"