Python List index() Method Explained with Examples | DataCamp
Skip to main content

Python List index() Method Explained with Examples

Learn how to use Python's index() function to find the position of elements in lists.
· 6 min read

Explore with AI

In Python, a data structure helps you organize and store data efficiently. One common and versatile structure is a list, which can hold different types of data in a specific order. Python also provides many functions or methods for working with lists.

In this tutorial, you will learn about the Python index() function. The index() method searches an element in the list and returns its position/index. First, this tutorial will introduce you to lists, and then you will see some simple examples of how to work with the index() function.

To easily run all the example code in this tutorial yourself, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples.

What is Indexing in Python?

In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number. Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on. For example, if we have a string "Hello", we can access the first letter "H" using its index 0 by using the square bracket notation: string[0].

Python's built-in index() function is a useful tool for finding the index of a specific element in a sequence. This function takes an argument representing the value to search for and returns the index of the first occurrence of that value in the sequence.

If the value is not found in the sequence, the function raises a ValueError. For example, if we have a list [1, 2, 3, 4, 5], we can find the index of the value 3 by calling list.index(3), which will return the value 2 (since 3 is the third element in the list, and indexing starts at 0).

The index() function is a powerful tool in Python as it simplifies the process of finding the index of an element in a sequence, eliminating the need for writing loops or conditional statements. This function is especially useful when working with large datasets or complex structures, where manual searching could be time-consuming and error-prone.

What is the index() Function?

The method index() returns the lowest index in the list where the element searched for appears.

Let's try it out:

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 3
print(list_numbers.index(element)) # 2

If any element which is not present is searched, it returns a ValueError.

list_numbers = [4, 5, 6, 7, 8, 9, 10]
element = 3 # Not in the list
print(list_numbers.index(element)) # Throws a ValueError

Working with Strings

Let's try it with string elements:

list_numbers = [1, 'two', 3, 4, 5, 6, 7, 8, 9, 10]
element = 'two'
print(list_numbers.index(element)) # 1

Note: When searching strings, index() is case-sensitive. For example, 'Hello'.index('h') will raise a ValueError.

Finding the First Occurrence

Imagine you have more than one instance of an element, then index() will give you the first position where the element appears.

list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
element = 3
print(list_numbers.index(element)) # 0

The position returned is 0, because 3 first appears in the first position or the 0th index in Python.

Here is what's happening internally: The index is going through all values starting from the 1st position (0th index), looking for the element you are searching for. When it finds the value - it returns the position and exits the system. However, this is not too efficient when going through a large list, and you need to get the position of something towards the end of the list.

Using Start and Stop Parameters

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
print(list_numbers.index(element, 5, 8)) # 6

So the syntax is: list_name.index(element, start, stop).

Here the start and stop values are optional. In fact, only use it when entirely sure about the range; otherwise, you will get a ValueError, as shown below.

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
print(list_numbers.index(element, 1, 5)) # Throws a ValueError

Finding All Occurrences

Since the index() only returns the first match to an object, you can use list comprehension, or generator expression if you need the positions of more matches in the list. Here is how:

list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]

# List comprehension
print([i for i, n in enumerate(list_numbers) if n == 3]) # [0, 3, 4, 8]
list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
g = (i for i, n in enumerate(list_numbers) if n == 3) # Generator expression

print("Generators store values, the first value here is:", next(g), ". Then the next is:", next(g), "followed by ", next(g),"and finally ", next(g))

# Generators store values, the first value here is: 0. Then the next is: 3 followed by  4 and finally  8

Generators are memory-efficient because they yield items one at a time instead of storing all results like list comprehensions.

Final Thoughts

Congrats, you have just learned about the index() function in Python! You have seen how it can help you work with lists. You have been introduced to some new concepts as well. For more on list comprehension, check out our Python List Comprehension tutorial. Our Python Iterator Tutorial has more on generators and generator expressions.

Sejal Jaiswal

Author

Sejal Jaiswal

I have worked in various industries and have worn multiple hats: software developer, machine learning researcher, data scientist, product manager. But at the core of it all, I am a programmer who loves to learn and share knowledge!

FAQs

What happens if multiple values match the element I'm searching for?

The index() method only returns the index of the first occurrence of the matching element. If you need all positions, use a list comprehension with enumerate().

Can I use index() with tuples or strings?

Yes! The index() method works on any sequence type, including tuples and strings:

my_tuple = (1, 2, 3, 2)
print(my_tuple.index(2))  # Output: 1

text = "hello world"
print(text.index('o'))    # Output: 4
Is there a way to handle ValueError gracefully?

Yes, wrap the index() call in a try...except block to avoid crashes if the element is not found:

my_list = [1, 2, 3]
try:
    print(my_list.index(4))
except ValueError:
    print("Element not found.")
How can I search from the end of the list?

The index() method doesn’t support reverse searching. To find the last occurrence, reverse the list manually or use a comprehension:

my_list = [1, 2, 3, 2, 1]
last_index = len(my_list) - 1 - my_list[::-1].index(2)
print(last_index)  # Output: 3
How is index() different from find()?

The find() method is used with strings and returns -1 instead of raising an error when the value is not found. Lists do not have a find() method.

text = "hello"
print(text.find('e'))  # Output: 1
print(text.find('z'))  # Output: -1
Can I use index() with nested lists?

Yes, but only at the top level. index() doesn’t search inside nested structures.

nested_list = [[1, 2], [3, 4]]
print(nested_list.index([3, 4]))  # Output: 1
# This won't work: nested_list.index(3)
What is the "list index out of range" error?

It occurs when code tries to access an index outside a list's valid range. A list with 5 elements only has valid indices 0 through 4, so requesting index 5 or higher raises this error. Checking an index against len() before accessing it prevents the error.

What is the "list indices must be integers" error?

It occurs when a non-integer value, such as a float or string, is used as a list index. Lists only accept integer indices, so passing anything else triggers this error. Converting the value with int() before indexing resolves the issue.

Topics

Related

Tutorial

Python Arrays