Skip to content

Python list index Function | Find the index of an element

  • by

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.

Syntax

list.index(element)

OR

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.

Return value

The method returns the index of the element in the list.

Example:

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)

Output: 1

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)
Python list index Function

Do comment if you have suggestions and doubts about this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading