Skip to content

Python find the position/index of an element in List

  • by

To find a position of the particular element you can use the index() method of List class with the element passed as an argument. An index() function returns an integer (position) of the first match of the specified element in the List.

Let’s see Examples of Find index of Elements in the list

Example 1: Only one value present in the List

See the example of using the index() method to find the index of the item 4 in the list.

my_list = [2, 9, 4, 5, 3, 5]
item = 4

# search for the item
index = my_list.index(item)

print('The index of', item, 'in the list is:', index)

Output:

The index of 4 in the list is: 2

Example 2: when an element is present multiple times in List

Python list can have the same value multiple times, so if you are finding any index of any value, and value have multiple occurrences. In such cases, only the index of the first occurrence of the specified element in the list is returned.

The list has 4 numbers two times and the first one is in index 0.

my_list = [4, 2, 9, 4, 5, 3, 5]
item = 4

# search for the item
index = my_list.index(item)

print('The index of', item, 'in the list is:', index)

Output:

The index of 4 in the list is: 0

Q: What if trying to find an index of elements and it’s not present in the List?

Answer: If you are using an index() function and the element searching in the list is 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)

Output:

Python find position index element List

Do comment if you have any doubts and suggestions on 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