How to check if the nth element in a Python list?

I have a list in python

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

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

How should I do it?

+8
python list
Mar 21 '13 at 17:30
source share
2 answers

You check the length:

 len(x) >= 4 

or you will catch an IndexError exception:

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

What you use depends on how often you can expect that there will be a fourth value. If this is usually the case, use an exception handler (it is better to ask for forgiveness); if you basically don't have a 4th value, check the length (look before you jump).

+20
Mar 21 '13 at 17:31
source share

Do you want to check if the list has 4 or more items?

 len(x) >= 4 

Do you want to check if the fourth element is in a row?

 'd' in x 
+3
Mar 21 '13 at 17:32
source share



All Articles