Python List index()

Python List index()

The index() method returns the index position of the searched given element in the list.

example for index() method

To find the index of a given element, use the index() method of Python Lists as shown below. # find index of element using index() method letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] myIndex = letters.index('e') print(myIndex) In this example, the letters list contains the letters from 'a' to 'g' in alphabetical order. The index() method is called and the letter 'e' is passed as argument, the return value is assigned to the variable myIndex. Then myIndex is printed and it contains the index position of the letter 'e' in the letters list. 4

syntax of index()

The syntax of the List index() method is: list.index(element[, start, end])

arguments of index()

The index() method accepts between one and three arguments. The first argument is required, the second and third are optional.
argument required description
element required the element to be searched in the list
start optional start search from this index position
end optional search up to this index position

return value of index()

The index() method returns the index position of the given element as integer. Only the first occurrence of the element is returned, even if the element occurs more than once within the list. If the element is not found within the list, a ValueError exception is raised.



Click to jump to section