Python list index Function is very useful to find an element in the list. Actually, the index() function finds the given element in a list and returns its position.
Note: Python index method returns the position at the first occurrence of the specified value and List indexing starts from 0, not 1.
list_name.index(element, start, end)
- element – The element whose lowest index will be returned.
- start (Optional) – The position from where the search begins.
- end (Optional) – The position from where the search ends.
The method returns the index of the element in the list.
A below code is for finding the index of the element in the list python.
nums = [14, 5, 4, 5, 7, 32] x = nums.index(5) print(x)
Q: How do Python find an index of all occurrences in a list?
Answer: You can use a list comprehension:
nums = [14, 5, 4, 5, 7, 32, 5] indices = [i for i, x in enumerate(nums) if x == 5] print(indices)
Output: [1, 3, 6]
Read More:- Important example of Python find the position/index of an element in List.
Q: What if Python finds a position in the list not found?
Answer: Using index() function to find the element in the list and if it’s not present, you will get a
ValueError with the message
item is not in list.
my_list = [4, 2, 9, 4, 5, 3, 5] item = 7 # search for the item index = my_list.index(item) print('The index of', item, 'in the list is:', index)
Do comment if you have suggestions and doubts about this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.