Skip to content

Python find index of element in list

  • by

Use the built-in index() function to find an index of an element in the list in Python. It returns a zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

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

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list.

Python finds an index of the element in a list example

Simple example code.

list1 = ["foo", "bar", "baz"]

res = list1.index("bar")
print("Index of bar:", res)


Python find index of element in list

let’s see an example using the other two start and stop parameters.

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# Searching for “o” within index 1-5
print(vowels.index("o", 1, 5))

# Searching for “o” within index 1-3
print(vowels.index("o", 0, 2)) # error

Do comment if you have any doubts or suggestions on this Pythono list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *