Sentry Answers>Python>

Get the index of a list item in Python

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:

Click to Copy
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.

Click to Copy
mylist = ["run", "hop", "bop"] try: print(mylist.index("hop")) # will print 1 except ValueError: print('"hop" not present')
Click to Copy
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:

Click to Copy
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.

  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Syntax.fmListen to the Syntax Podcast
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

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