Quicksilver
Quicksilver

Reputation: 2700

How to check whether a list index is present or not

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

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

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

eumiro
eumiro

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

ATOzTOA
ATOzTOA

Reputation: 35950

You can always check:

if index < len(a):
    # do stuff

Upvotes: 3

Related Questions