How to find what is the index of an element in a list in Python?

PythonServer Side ProgrammingProgramming

The index() method available to List (as well as other sequence type such as string and tuple) is useful to find first occurrence of a particular element in it.

>>> L1=['a', 'b', 'c', 'a', 'x']
>>> L1
['a', 'b', 'c', 'a', 'x']
>>> L1.index('a')
0

To obtain indexes of all occurrences of an element, create enumerate object (which presents iterator for index and value of each element in list)

>>> for i,j in enumerate(L1):
if j=='a':
print (i)


0
3
raja
Published on 02-Jan-2018 23:38:07
Advertisements