Question
Given a Python list such as:
items = ["foo", "bar", "baz"]
and a value that exists in the list:
item = "bar"
how can you get the index of that item, so the result is:
1
Short Answer
By the end of this page, you will understand how to find the position of a value in a Python list using list.index(), what happens when the value is missing, and how this is commonly handled in real Python code.
Concept
In Python, a list index is the numeric position of an element inside a list. Indexes start at 0, not 1.
For example:
items = ["foo", "bar", "baz"]
The positions are:
"foo"→ index0"bar"→ index1"baz"→ index2
To find the index of a value, Python lists provide the built-in method:
list.index(value)
Example:
items = ["foo", "bar", "baz"]
print(items.index("bar"))
Output:
1
This matters because many programming tasks depend on knowing where something appears in a sequence:
Mental Model
Think of a list like a row of numbered lockers.
["foo", "bar", "baz"]
The lockers are numbered:
- locker
0has"foo" - locker
1has"bar" - locker
2has"baz"
When you call items.index("bar"), you are asking:
"Which locker number contains
"bar"?"
Python searches from left to right and returns the first matching locker number.
Syntax and Examples
The basic syntax is:
my_list.index(value)
You can also search within part of a list:
my_list.index(value, start, end)
Basic example
items = ["foo", "bar", "baz"]
index = items.index("bar")
print(index)
Output:
1
index() returns the position of the first matching element.
Example with numbers
numbers = [10, 20, 30, 40]
print(numbers.index(30))
Output:
2
Example with duplicate values
letters = ["a", , , ]
(letters.index())
Step by Step Execution
Consider this code:
items = ["foo", "bar", "baz"]
result = items.index("bar")
print(result)
Step by step:
- Python creates a list:
["foo", "bar", "baz"] - The variable
itemsnow refers to that list. - Python evaluates:
items.index("bar") - It checks elements from left to right:
- index
0→"foo"→ not a match - index
1→"bar"→ match found
- index
- Python returns
1. - That value is stored in
result. print(result)displays:1
Here is another example showing failure:
Real World Use Cases
Finding an item’s index is useful in many practical situations:
User interface selections
menu = ["Home", "Profile", "Settings"]
selected = "Profile"
position = menu.index(selected)
This can help highlight the active tab.
Data processing
columns = ["id", "name", "email"]
email_index = columns.index("email")
This is useful when reading CSV-like data where column positions matter.
Reordering items
tasks = ["todo", "doing", "done"]
current = tasks.index("doing")
A program can use the index to move an item forward or backward.
Validation rules
allowed_steps = ["start", "review", "publish"]
step_index = allowed_steps.index("review")
This can help compare workflow order.
Command-line tools and scripts
A script may search a list of arguments, options, or headers to find where a value appears before processing it.
Real Codebase Usage
In real projects, developers often use list.index() in small, focused ways rather than everywhere.
Common pattern: find and use position
fields = ["name", "email", "age"]
pos = fields.index("email")
This is common when mapping field names to column positions.
Guarding against missing values
If the item may not exist, developers usually avoid assuming success:
if "email" in fields:
pos = fields.index("email")
This works, but note that it searches the list twice.
Error handling with try/except
try:
pos = fields.index("email")
except ValueError:
pos = None
This is common when missing data is expected.
Working with duplicates
When developers need all matching positions, they do not rely on index() alone:
Common Mistakes
Mistake 1: Forgetting that indexes start at 0
Broken expectation:
items = ["foo", "bar", "baz"]
print(items.index("bar")) # beginner may expect 2
Actual result:
1
Python uses zero-based indexing.
Mistake 2: Calling index() for a value that is not present
Broken code:
items = ["foo", "bar", "baz"]
print(items.index("qux"))
This raises:
ValueError
Avoid this by handling the error:
try:
print(items.index("qux"))
except ValueError:
print("Not found")
Mistake 3: Assuming index() returns all matches
Comparisons
| Concept | What it does | Best use case |
|---|---|---|
list.index(value) | Finds the first index of a given value | You know the value and want its position |
my_list[i] | Gets the value at a known index | You already know the position |
in | Checks whether a value exists | You only need True/False |
enumerate(my_list) | Gives both index and value while looping | You want to iterate with positions |
index() vs in
items = ["foo", "bar", "baz"]
print( items)
(items.index())
Cheat Sheet
items = ["foo", "bar", "baz"]
items.index("bar") # 1
Syntax
my_list.index(value)
my_list.index(value, start)
my_list.index(value, start, end)
Rules
- Indexes start at
0 index()returns the first match- If the value is missing, Python raises
ValueError - Search happens from left to right
Safe pattern
try:
i = my_list.index(value)
except ValueError:
i = None
Get all matching indexes
[i for i, v in enumerate(my_list) if v == value]
Useful related tools
in→ check if a value existsenumerate()→ loop with index and value
FAQ
How do I find the index of an item in a Python list?
Use list.index():
items = ["foo", "bar", "baz"]
print(items.index("bar"))
What happens if the item is not in the list?
Python raises a ValueError. Use try/except if the value may be missing.
Does index() return the first or last match?
It returns the first matching index.
How do I find all indexes of the same value?
Use enumerate() with a list comprehension:
[i for i, v in enumerate(items) if v == "bar"]
Why is the index of the second item equal to 1?
Because Python uses zero-based indexing, so counting starts at 0.
Can I search only part of a list?
Yes:
Mini Project
Description
Build a small Python script that searches a list of product names and reports the position of a chosen product. This demonstrates how to use list.index() in a practical lookup task and how to safely handle missing values.
Goal
Create a program that finds a product's index in a list and prints a helpful message if the product does not exist.
Requirements
- Create a list of at least five product names.
- Search for one product that exists in the list.
- Search for one product that does not exist in the list.
- Print the index when a product is found.
- Print a clear message when a product is not found.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.