Friday, 4 December 2015

Python: list: index: Get index of element

list.index(x)
‘list’ provides index method, which returns the index of the first item whose value is x.

test.py

list=[2, 4, 6, 6, 4, 2]
print(list)

print("index of 2 is ", list.index(2))
print("index of 4 is ", list.index(4))
print("index of 6 is ", list.index(6))

$ python3 test.py
[2, 4, 6, 6, 4, 2]
index of 2 is  0
index of 4 is  1
index of 6 is  2

Throws an error, if element is not in the list.
test.py

list=[2, 4, 6, 6, 4, 2]
print(list)

print("index of 20 is ", list.index(20))


$ python3 test.py
[2, 4, 6, 6, 4, 2]
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print("index of 20 is ", list.index(20))
ValueError: 20 is not in list





Previous                                                 Next                                                 Home

No comments:

Post a Comment