How to check if the n-th element exists in a Python list?

后端 未结 2 944
南笙
南笙 2021-02-07 21:03

I have a list in python

x = [\'a\',\'b\',\'c\']

with 3 elements. I want to check if a 4th element exists without receiving an error message.

2条回答
  •  轮回少年
    2021-02-07 21:39

    You check for the length:

    len(x) >= 4
    

    or you catch the IndexError exception:

    try:
        value = x[3]
    except IndexError:
        value = None  # no 4th index
    

    What you use depends on how often you can expect there to be a 4th value. If it is usually there, use the exception handler (better to ask forgiveness); if you mostly do not have a 4th value, test for the length (look before you leap).

提交回复
热议问题