PythonLists and tuples
list. index()
Returns the index of the first occurrence of a value in a list.
- Returns
- The index of the first occurrence.
- Changes the original
- No
Example
#Python
ranking = ["Emma", "Mia", "Jack", "Mia"]
print(ranking.index("Mia"))
print(ranking.index("Mia", 2))
name = "Noah"
print(ranking.index(name) if name in ranking else "not in the ranking")Resultsaved result, you can check it
1
3
not in the ranking
Definition and usage
#The index(x) method returns the position of the first item equal to x. The optional start and end arguments limit the part of the list that gets searched.
If the value is missing, a ValueError is raised, instead of returning -1 like a string’s find() method does. That is why it is worth checking with the in operator before calling it.
The search goes through the items one by one, so it can be slow on very large lists. For frequent lookups, a dictionary is a better choice.
Syntax
#Syntax
list.index(value, start=0, end=len(list))Parameters
#value
any value
The value to search for.start, end
int, optional
The range to search within.
Good practices
#- Check with
inbeforeindex()to avoid the exception. - When you need the indexes of every occurrence:
[i for i, x in enumerate(items) if x == value].
Related entries
#Spotted a mistake or missing an example? Write to us.