Reputation: 2700
I have the following list
a = ['a','c','d']
I need to check whether the list index 4(or any index) is present on the list or not. Is there a method similar to php isset in python for this(without using exception handling)?
Upvotes: 1
Views: 227
Reputation: 250951
You can use len()
to check whether the Index is present or not.
As len(list)
returns something like last_index+1
:
In [18]: a = ['a','c','d']
In [19]: len(a)-1 > 4 #or len(a)>4
Out[19]: False
In [20]: len(a)-1 > 2
Out[20]: True
Upvotes: 4
Reputation: 212875
if len(a) > 4:
# list contains fourth element, a[4]
or
try:
a[4] # do something with a[4]
except IndexError:
print "there is no element a[4]"
Upvotes: 6