Skip to main content

Python List Index()

In this tutorial, you will learn exclusively about the index() function.
Jul 2018  · 6 min read
banner

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. Lists 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 exclusively about the 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. Stick around till the very end, to learn some additional cool stuff...

Lists

Lists are written within square brackets [ and ], and the items within it are separated by a comma (,). Lists are mutable store collection of heterogeneous items. Let's break the statement down: what does mutable mean? Mutable means that you can change the content of a list without actually changing its identity. What do heterogeneous items mean? It means lists can hold mixed values within itself, such as integers, floats, strings, etc. Lists are built into Python, and you do not need to invoke them separately. Lets first define a list:

list_x = [] #Empty list
list_x # Print the list to see its contents
[]
list_x = [1, 'two', 3.0]
list_x
[1, 'two', 3.0]
list_y = [1, 2, 3]
list_y
[1, 2, 3]

All of the above are examples of lists. list_x is a list of heterogeneous items since it holds integers, strings as well as floats. Whereas list_y holds homogeneous items - integers only.

Now, let's say you needed to access the string value 'two' from list_x for an operation. Here is how you would do it:

value = list_x[1]
print('How do you spell 2?', value)
How do you spell 2? two

The list index starts with 0 in Python. So, the index value of 1 is 0, 'two' is 1 and 3 is 2.

But what if you knew the value you wanted to access but didn't know where it would show up in the list? Or if it even existed in the list? This is when the index() method comes in handy....

Index

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

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

Bonus: 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

The End!

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.

Introduction to Python

Beginner
4 hours
4,586,336
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

Intermediate Python

Beginner
4 hours
880,684
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Python Data Science Toolbox (Part 2)

Beginner
4 hours
224,939
Continue to build your modern Data Science skills by learning about iterators and list comprehensions.
See all coursesRight Arrow
Related

The 23 Top Python Interview Questions & Answers

Essential Python interview questions with examples for job seekers, final-year students, and data professionals.
Abid Ali Awan's photo

Abid Ali Awan

22 min

Working with Dates and Times in Python Cheat Sheet

Working with dates and times is essential when manipulating data in Python. Learn the basics of working with datetime data in this cheat sheet.
DataCamp Team's photo

DataCamp Team

Plotly Express Cheat Sheet

Plotly is one of the most widely used data visualization packages in Python. Learn more about it in this cheat sheet.
DataCamp Team's photo

DataCamp Team

0 min

Getting started with Python cheat sheet

Python is the most popular programming language in data science. Use this cheat sheet to jumpstart your Python learning journey.
DataCamp Team's photo

DataCamp Team

8 min

Python pandas tutorial: The ultimate guide for beginners

Are you ready to begin your pandas journey? Here’s a step-by-step guide on how to get started. [Updated November 2022]
Vidhi Chugh's photo

Vidhi Chugh

15 min

Python Iterators and Generators Tutorial

Explore the difference between Python Iterators and Generators and learn which are the best to use in various situations.
Kurtis Pykes 's photo

Kurtis Pykes

10 min

See MoreSee More