From this tutorial, you will be learning about Python list Index method. You will see how to use it on sequences with the help of examples.
Note: The syntax used in the below section is for Python 3. You can change it to any other versions of Python.
Python List Index
To Learn about Lists – Read Python List
List Index Method
The Index function is a built-in list method that allows you to find out the index or position of an element in a sequence.
In other words, this method searches for an element in the list and returns its index.
Its syntax is as follows:
It takes the element as an argument and returns the index. Please note that you can provide any input such as a list or a tuple or a substring.
See the below example.
>>> myList = ['1', '11', 1, 'a', 'x', 1.1] >>> myList.index(1) 2 >>> myList.index('x') 4
How does the Index() function work?
It takes one input which is the element for which you want the index or position as the output.
This method searches for the element in the list and returns the index matches its value else raises the ValueError error.
While searching for substrings, it raises the following error.
"Substring not found"
>>> first = 'Python is the language of the future.' >>> print(first.index('lang', 10)) 14 >>> print(first.index('invalid', 10)) Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> print(first.index('invalid', 10)) ValueError: substring not found >>>
The flowcharts below attempt to explain it in a diagram:
For elements in the list:
For characters in the string:
Using the wrong element
myList = [2,3,4,5,6] myList.index(1)
The output is:
Traceback (most recent call last): File "C:\Python\Python35\test.py", line 3, in <module> myList.index(1) ValueError: 1 is not in list
Find the element index in a tuple
myList = [2,3,(3,4),5] print(myList.index((3,4)))
The result is: