Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

How would I do that?

like image 985
A B Avatar asked Mar 21 '13 17:03

A B


Video Answer


2 Answers

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).

like image 183
Martijn Pieters Avatar answered Sep 17 '22 16:09

Martijn Pieters


You want to check if the list is 4 or more elements long?

len(x) >= 4

You want to check if what would be the fourth element in a series is in a list?

'd' in x
like image 26
Silas Ray Avatar answered Sep 20 '22 16:09

Silas Ray