Find index of an element in a list Python

How to find index of an element in a list – Python ?

This tutorial will guide you on how to find index of an element in a list using lists data structures in Python programming language.

Find index of an element in a list – Python

Find index of an element in a list Python

Below example shows how to find index of an element in a list of integers.

For example,

numbers = [4, 6, 10, 24, 28, 30]
numbers.index(10)
2

Note, the syntax for list.index is as follows:

list.index(x[, start[, end]])

It returns zero-based index in the list of first item whose value is x. If there is no such element specified, this method will throw ValueError as shown below.

>>> numbers.index(101)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 101 is not in list

If the value x is repeated more than once in the list, then you can use start and end indices to find the required index.

For example,

# 4 is repeated thrice in the list
>>> num = [4, 6, 4, 10, 24, 4, 28, 30]

>>> num.index(4)
0

#find next 4 starting from a position 1
>>> num.index(4, 1)
2

#find next 4 starting from a position 3
>>> num.index(4, 3)
5

Note, the arguments start and end are optional as we saw in slice notation. And they are used to limit our search to a particular sub-sequence of the given list.

Similarly, you can find index of an item in a list (string array) as shown below.

For example,

strArray = ['apple', 'boy', 'cat', 'dog', 'elephant']
strArray.index('cat')
2

Time Complexity – list.index()

When you call list.index() it checks every element of the list in order until it finds the value specified. Therefore, if your list is long and you don’t know roughly the next occurrence of the value, then the search will become a bottleneck and it takes more time.

Hence you should consider different data structure if the given list is lengthy.

That’s it. You had learnt how to find index of an element in a list using Python programming language.

Hope it is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments