# Get index of list item in Python - And get indexes by list comprehension

Python list has index method that returns the index of an item.

a = ['book', 'car', 'pen']

i = a.index('book')
j = a.index('pen')
k = a.index('car')

print(i)  # 0
print(j)  # 2
print(k)  # 1


book is the first of a so the index of it is 0. The index of pen is 2.

book ... 0
car ... 1
pen ... 2

If a list doesn't contain any item, Python raises the ValueError exception.

a = ['book', 'car', 'pen']

i = a.index('moon')
# ValueError: 'moon' is not in list


## Note: string and index

a = 'computer'

x1 = a.index('c')
x2 = a.index('ter')

print(x1)  # 0
print(x2)  # 5


index returns the index of a substring in the string in the same way as list.

## Index of the same elements

index returns only the index of the first found item.

a = [1, 2, 3, 1, 1]

m = a.index(1)

print(m)  # 0


There are many 1, but this method only returns the first index (=0). How can we get all the indexes of the element. Let's use list comprehension.

a = [1, 2, 3, 1, 1]

b1 = [index for index, value in enumerate(a) if value == 1]
b2 = [index for index, value in enumerate(a) if value == 2]
b3 = [index for index, value in enumerate(a) if value == 3]

print(b1)  # [0, 3, 4]
print(b2)  # [1]
print(b3)  # [2]


To iterate the index and value of a list, use enumerate.

0 -> 1
3 -> 1
4 -> 1

It's true that the value of with index 0, 3, or 4 is 1. index returns the first index of b1.