The index method of lists in Python

The index method finds the first occurrence of a list item and returns its index.
If the item isn’t in the list, it raises a ValueError.

letters = ['a', 'z', 'p', 'd', 'k']
print(letters.index('p'))
print(letters.index('k'))

It works the same if the items are numbers as well:

numbers = [9, 11, 45, 2, 38, 195]
print(numbers.index(11))
print(numbers.index(195))

The output in the terminal will be:

>>> letters = ['a', 'z', 'p', 'd', 'k']
>>> print(letters.index('p'))
2
>>> print(letters.index('k'))
4
>>> numbers = [9, 11, 45, 2, 38, 195]
>>> print(numbers.index(11))
1
>>> print(numbers.index(195))
5

Note:
There are several very useful functions and methods for lists. There most useful are:

  • max(list) – Returns the list item with the maximum value
  • min(list) – Returns the list item with minimum value
  • list.count(obj) – Returns a count of how many times an item occurs in a list
  • list.remove(obj) – Removes an object from a list
  • list.reverse() – Reverses objects in a list

Leave a Reply