Skip to main content
HomeTutorialsPython

Python List Index() Tutorial

In this tutorial, you will learn exclusively about the index() function.
Updated Feb 2023  · 6 min read

A data structure is a way to organize and store data that enables efficient access and modification. Lists are a type of data structure that store a collection of heterogeneous items and are inbuilt data structures. Python also provides many functions or methods that you can use to work 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 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.

Learn Python From Scratch

Master Python for data science and gain in-demand skills.
Start Learning for Free

Python Index Examples

The method index() returns the lowest index in the list where the element searched for appears. If any element which is not present is searched, it returns a ValueError.

Lets try this:

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

ValueError                                Traceback (most recent call last)

<ipython-input-35-6a006c988b06> in <module>()
      1 list_numbers = [4, 5, 6, 7, 8, 9, 10]
      2 element = 3 # Not in the list
----> 3 list_numbers.index(element) # Throws a ValueError


ValueError: 3 is not in list

Index of a string element

Let's try it with string elements:

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

What does it mean to return the lowest index?

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
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: index is going through all values starting from the 1st position (0th index) looking for the element you are searching for, and as soon as 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.

index() provides you an option to give it hints to where the value searched for might lie

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
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 else you will get a ValueError as below.

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

ValueError                                Traceback (most recent call last)

<ipython-input-39-b96f4b5e51d5> in <module>()
      1 list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      2 element = 7
----> 3 list_numbers.index(element, 1, 5)


ValueError: 7 is not in list

List Comprehension or Generator Expression

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]
[i for i, n in enumerate(list_numbers) if n == 3] # List comprehension
[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

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 DataCamp's Python List Comprehension tutorial. DataCamp's Python Iterator Tutorial has more on generators and generator expressions.

Get certified in your dream Data Scientist role

Our certification programs help you stand out and prove your skills are job-ready to potential employers.

Get Your Certification
Timeline mobile.png

Python List Index FAQs

What is the "list index out of range" error?

The "list index out of range" error occurs when you try to access an index that is outside the range of valid indices for a list. For example, if a list has 5 elements, the valid indices are 0 to 4. If you try to access an index greater than or equal to 5, you will get this error.

To avoid the "list index out of range" error, you should make sure that the index you are trying to access is within the range of valid indices for the list. You can use the len() function to get the length of a list and check if an index is within the range of valid indices.

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

The "list indices must be integers" error occurs when you try to use a non-integer value as a list index. For example, if you try to use a floating-point number or a string as a list index, you will get this error.

To avoid the "list indices must be integers" error, you should make sure that you are using an integer value as a list index. If you need to use a non-integer value as an index, you can convert it to an integer using the int() function.

How can I find the index of an element in a list?

You can use the index() method of a list to find the index of a specific element. For example, if my_list is a list and my_element is an element in the list, you can find the index of my_element with my_list.index(my_element).

How can I find all the indices of an element in a list?

You can use a list comprehension to find all the indices of an element in a list. For example, if my_list is a list and my_element is an element in the list, you can find all the indices of my_element with [i for i in range(len(my_list)) if my_list[i] == my_element].

Topics

Python Courses

Course

Introduction to Python

4 hr
5.7M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Python List Functions & Methods Tutorial and Examples

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Abid Ali Awan's photo

Abid Ali Awan

7 min

tutorial

Python Range() Function Tutorial

Learn about the Python Range() function and its capabilities with the help of examples.
Aditya Sharma's photo

Aditya Sharma

7 min

tutorial

Python Count Tutorial

Learn how to use the counter tool with an interactive example.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Python Functions Tutorial

A tutorial on functions in Python that covers how to write functions, how to call them, and more!
Karlijn Willems's photo

Karlijn Willems

14 min

tutorial

Python String Tutorial

In this tutorial, you'll learn all about Python Strings: slicing and striding, manipulating and formatting them with the Formatter class, f-strings, templates and more!
Sejal Jaiswal's photo

Sejal Jaiswal

16 min

tutorial

Python String format() Tutorial

Learn about string formatting in Python.
DataCamp Team's photo

DataCamp Team

5 min

See MoreSee More