Get the index of a list item in Python

David Y.

The Problem

Given a list ["run", "hop", "bop"], how do I get the index of the item “hop” in Python?

The Solution

We can use Python’s list.index() method to return the index of a given item:

mylist = ["run", "hop", "bop"] print(mylist.index("hop")) # will print 1

If the given item is not found in the list, a ValueError will be raised. Therefore, we need to either wrap our function call in a try/except block or first check whether the item is in the list.

mylist = ["run", "hop", "bop"] try: print(mylist.index("hop")) # will print 1 except ValueError: print('"hop" not present')
mylist = ["run", "hop", "bop"] if "hop" in mylist: print(mylist.index("hop")) # will print 1 else: print('"hop" not present')

list.index() works by checking every element of the list, starting at the first one, until it finds a match. For long lists, this could take a long time. Fortunately, the method provides start and end arguments, which can be specified to limit the search to a portion of the list, speeding up the search in some instances.

If the specified item occurs multiple times, list.index() will only return the index of the first occurrence. In some cases, this may be desirable. Otherwise, if you want to return the indexes of every occurrence, you can use a list comprehension:

mylist_extended = ["run", "hop", "bop", "hop"] indices = [index for index, element in enumerate(mylist_extended) if element == "hop"] print(indices) # will print [1, 3]

If the element is not present in mylistextended, indices will be an empty list.

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key><project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.