• Register

Python knows variety of compound data types, wont to group together other values. the foremost versatile is that the list, which may be written as an inventory of comma-separated values (items) between square brackets. Lists might contain items of various types, but usually the things all have an equivalent type.

How to find the index of an element in a list

The list API contains index as an weak component. Henceit checks every element of the list in order, until it finds a match so that it have linear time-complexity in list length.

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

Return zero-based index within the list of the primary item whose value is adequate to x. Raises a ValueError if there's no such item.

The optional arguments start and end are interpreted as within the slice notation and are wont to limit the search to a specific subsequence of the list. The returned index is computed relative to the beginning of the complete sequence instead of the start argument. For example:

>>> ["foo", "bar", "baz"].index("bar")
1

If there expectation to need indices of more matches, then it should use a list comprehension, or generator expression.

>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2

If your list is long, and you do not know roughly where within the list it occurs, this search could become a bottleneck. therein case, you ought to consider a special arrangement.

3 Comments

You never know what you will get on the internet. It is full of surprises like this amazing blog post.
Please expand on this subject. Your ability to explain things is wonderful.
Please write more on this topic. Your explanation skill is amazing.

More Posts

How to find the index of an element in a list python Tania - Jul 12
Solution on Finding index of first occurrence in list - Python hubconcepts - Oct 21, 2020
How to find the number of unique elements in list in Python mhfaisal - Jul 14
How to append to the beginning of a list python Tania - May 12
How to remove an index element from the vector in C++? Lalit Kumar - Aug 2, 2020
How to count number of items in list python Tania - May 8
Python check if an elements is in a list Tania - May 28
Removing element from a list python Tania - Feb 21
How to remove the last character of string in python. Tania - Jul 8
Python how to append to a list | by kodlogs Answer's... Tania - Apr 25