How can I check if a list index exists?

后端 未结 4 936
刺人心
刺人心 2021-01-17 07:59

Seems as though

if not mylist[1]:
    return False

Doesn\'t work.

4条回答
  •  轮回少年
    2021-01-17 08:01

    Alternative (but somewhat slower) way of doing it:

    if index not in range(len(myList)):
        return False
    

    It gets a bit more verbose when accounting for negative indices:

    if index not in range(-len(myList), len(myList)):
        return False
    

提交回复
热议问题