Finding the index of an item given a list containing it in Python
For a list
["foo", "bar", "baz"]
and an item in the list"bar"
, what’s the cleanest way to get its index (1) in Python?
Well, sure, there’s the index method, which returns the index of the first occurrence:
>>> l = ["foo", "bar", "baz"]
>>> l.index('bar')
1
There are a couple of issues with this method:
- if the value isn’t in the list, you’ll get a
ValueError
- if more than one of the value is in the list, you only get the index for the first one
No values
If the value could be missing, you need to catch the ValueError
.
You can do so with a reusable definition like this:
def index(a_list, value):
try:
return a_list.index(value)
except ValueError:
return None
And use it like this:
>>> print(index(l, 'quux'))
None
>>> print(index(l, 'bar'))
1
And the downside of this is that you will probably have a check for if the returned value is
or is not
None:
result = index(a_list, value)
if result is not None:
do_something(result)
More than one value in the list
If you could have more occurrences, you’ll not get complete information with list.index
:
>>> l.append('bar')
>>> l
['foo', 'bar', 'baz', 'bar']
>>> l.index('bar') # nothing at index 3?
1
You might enumerate into a list comprehension the indexes:
>>> [index for index, v in enumerate(l) if v == 'bar']
[1, 3]
>>> [index for index, v in enumerate(l) if v == 'boink']
[]
If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:
indexes = [index for index, v in enumerate(l) if v == 'boink']
for index in indexes:
do_something(index)
Better data munging with pandas
If you have pandas, you can easily get this information with a Series object:
>>> import pandas as pd
>>> series = pd.Series(l)
>>> series
0 foo
1 bar
2 baz
3 bar
dtype: object
A comparison check will return a series of booleans:
>>> series == 'bar'
0 False
1 True
2 False
3 True
dtype: bool
Pass that series of booleans to the series via subscript notation, and you get just the matching members:
>>> series[series == 'bar']
1 bar
3 bar
dtype: object
If you want just the indexes, the index attribute returns a series of integers:
>>> series[series == 'bar'].index
Int64Index([1, 3], dtype='int64')
And if you want them in a list or tuple, just pass them to the constructor:
>>> list(series[series == 'bar'].index)
[1, 3]
Yes, you could use a list comprehension with enumerate too, but that’s just not as elegant, in my opinion – you’re doing tests for equality in Python, instead of letting builtin code written in C handle it:
>>> [i for i, value in enumerate(l) if value == 'bar']
[1, 3]
Is this an XY problem?
The XY problem is asking about your attempted solution rather than your actual problem.
Why do you think you need the index given an element in a list?
If you already know the value, why do you care where it is in a list?
If the value isn’t there, catching the ValueError
is rather verbose – and I prefer to avoid that.
I’m usually iterating over the list anyways, so I’ll usually keep a pointer to any interesting information, getting the index with enumerate.
If you’re munging data, you should probably be using pandas – which has far more elegant tools than the pure Python workarounds I’ve shown.
I do not recall needing list.index
, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.
There are many, many uses for it in idlelib
, for GUI and text parsing.
The keyword
module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.
In Lib/mailbox.py it seems to be using it like an ordered mapping:
key_list[key_list.index(old)] = new
and
del key_list[key_list.index(key)]
In Lib/http/cookiejar.py, seems to be used to get the next month:
mon = MONTHS_LOWER.index(mon.lower())+1
In Lib/tarfile.py similar to distutils to get a slice up to an item:
members = members[:members.index(tarinfo)]
In Lib/pickletools.py:
numtopop = before.index(markobject)
What these usages seem to have in common is that they seem to operate on lists of constrained sizes (important because of O(n) lookup time for list.index
), and they’re mostly used in parsing (and UI in the case of Idle).
While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you’re doing is the most direct usage of the tools provided by the language for your use-case.
In this article you will learn how to find the index of an element contained in a list in the Python programming language.
There are a few ways to achieve this, and in this article you will learn three of the different techniques used to find the index of a list element in Python.
The three techniques used are:
- finding the index using the
index()
list method, - using a
for-loop
, - and finally, using list comprehension and the
enumerate()
function.
Specifically, here is what we will cover in depth:
- An overview of lists in Python
- How indexing works
- Use the
index()
method to find the index of an item
1.Use optional parameters with theindex()
method - Get the indices of all occurrences of an item in a list
- Use a
for-loop
to get indices of all occurrences of an item in a list - Use list comprehension and the
enumerate()
function to get indices of all occurrences of an item in a list
- Use a
What are Lists in Python?
Lists are a built-in data type in Python, and one of the most powerful data structures.
They act as containers and store multiple, typically related, items under the same variable name.
Items are placed and enclosed inside square brackets, []
. Each item inside the square brackets is separated by a comma, ,
.
# a list called 'my_information' that contains strings and numbers
my_information = ["John Doe", 34, "London", 1.76]
From the example above, you can see that lists can contain items that are of any data type, meaning list elements can be heterogeneous.
Unlike arrays that only store items that are of the same type, lists allow for more flexibility.
Lists are also mutable, which means they are changeable and dynamic. List items can be updated, new items can be added to the list, and any item can be removed at any time throughout the life of the program.
An Overview of Indexing in Python
As mentioned, lists are a collection of items. Specifically, they are an ordered collection of items and they preserve that set and defined order for the most part.
Each element inside a list will have a unique position that identifies it.
That position is called the element’s index.
Indices in Python, and in all programming languages, start at 0
and not 1
.
Let’s take a look at the list that was used in the previous section:
my_information = ["John Doe", 34, "London", 1.76]
The list is zero-indexed and counting starts at 0
.
The first list element, "John Doe"
, has an index of 0
.
The second list element, 34
, has an index of 1
.
The third list element, "London"
, has an index of 2
.
The forth list element, 1.76
, has an index of 3
.
Indices come in useful for accessing specific list items whose position (index) you know.
So, you can grab any list element you want by using its index.
To access an item, first include the name of the list and then in square brackets include the integer that corresponds to the index for the item you want to access.
Here is how you would access each item using its index:
my_information = ["John Doe", 34, "London", 1.76]
print(my_information[0])
print(my_information[1])
print(my_information[2])
print(my_information[3])
#output
#John Doe
#34
#London
#1.76
But what about finding the index of a list item in Python?
In the sections that follow you will see some of the ways you can find the index of list elements.
So far you’ve seen how to access a value by referencing its index number.
What happens though when you don’t know the index number and you’re working with a large list?
You can give a value and find its index and in that way check the position it has within the list.
For that, Python’s built-in index()
method is used as a search tool.
The syntax of the index()
method looks like this:
my_list.index(item, start, end)
Let’s break it down:
my_list
is the name of the list you are searching through..index()
is the search method which takes three parameters. One parameter is required and the other two are optional.item
is the required parameter. It’s the element whose index you are searching for.start
is the first optional parameter. It’s the index where you will start your search from.end
the second optional parameter. It’s the index where you will end your search.
Let’s see an example using only the required parameter:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("Python"))
#output
#1
In the example above, the index()
method only takes one argument which is the element whose index you are looking for.
Keep in mind that the argument you pass is case-sensitive. This means that if you had passed “python”, and not “Python”, you would have received an error as “python” with a lowercase “p” is not part of the list.
The return value is an integer, which is the index number of the list item that was passed as an argument to the method.
Let’s look at another example:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("React"))
#output
#line 3, in <module>
# print(programming_languages.index("React"))
#ValueError: 'React' is not in list
If you try and search for an item but there is no match in the list you’re searching through, Python will throw an error as the return value – specifically it will return a ValueError
.
This means that the item you’re searching for doesn’t exist in the list.
A way to prevent this from happening, is to wrap the call to the index()
method in a try/except
block.
If the value does not exist, there will be a message to the console saying it is not stored in the list and therefore doesn’t exist.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
try:
print(programming_languages.index("React"))
except ValueError:
print("That item does not exist")
#output
#That item does not exist
Another way would be to check to see if the item is inside the list in the first place, before looking for its index number. The output will be a Boolean value – it will be either True or False.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print("React" in programming_languages)
#output
#False
How to Use the Optional Parameters with the index()
Method
Let’s take a look at the following example:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python"))
#output
#1
In the list programming_languages
there are three instances of the “Python” string that is being searched.
As a way to test, you could work backwards as in this case the list is small.
You could count and figure out their index numbers and then reference them like you’ve seen in previous sections:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages[1])
print(programming_languages[3])
print(programming_languages[5])
#output
#Python
#Python
#Python
There is one at position 1
, another one at position 3
and the last one is at position 5
.
Why aren’t they showing in the output when the index()
method is used?
When the index()
method is used, the return value is only the first occurence of the item in the list. The rest of the occurrences are not returned.
The index()
method returns only the index of the position where the item appears the first time.
You could try passing the optional start
and end
parameters to the index()
method.
You already know that the first occurence starts at index 1
, so that could be the value of the start
parameter.
For the end
parameter you could first find the length of the list.
To find the length, use the len()
function:
print(len(programming_languages))
#output is 6
The value for end
parameter would then be the length of the list minus 1. The index of the last item in a list is always one less than the length of the list.
So, putting all that together, here is how you could try to get all three instances of the item:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python",1,5))
#output
#1
The output still returns only the first instance!
Although the start
and end
parameters provide a range of positions for your search, the return value when using the index()
method is still only the first occurence of the item in the list.
How to Get the Indices of All Occurrences of an Item in A List
Use a for-loop
to Get the Indices of All Occurrences of an Item in A List
Let’s take the same example that we’ve used so far.
That list has three occurrences of the string “Python”.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
First, create a new, empty list.
This will be the list where all indices of “Python” will be stored.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
Next, use a for-loop
. This is a way to iterate (or loop) through the list, and get each item in the original list. Specifically, we loop over each item’s index number.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
You first use the for
keyword.
Then create a variable, in this case programming_language
, which will act as a placeholder for the position of each item in the original list, during the iterating process.
Next, you need to specify the set amount of iterations the for-loop
should perform.
In this case, the loop will iterate through the full length of the list, from start to finish. The syntax range(len(programming_languages))
is a way to access all items in the list programming_languages
.
The range()
function takes a sequence of numbers that specify the number it should start counting from and the number it should end the counting with.
The len()
function calculates the length of the list, so in this case counting would start at 0
and end at – but not include – 6
, which is the end of the list.
Lastly, you need to set a logical condition.
Essentially, you want to say: “If during the iteration, the value at the given position is equal to ‘Python’, add that position to the new list I created earlier”.
You use the append()
method for adding an element to a list.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
if programming_languages[programming_language] == "Python":
python_indices.append(programming_language)
print(python_indices)
#output
#[1, 3, 5]
Use List Comprehension and the enumerate()
Function to Get the Indices of All Occurrences of an Item in A List
Another way to find the indices of all the occurrences of a particular item is to use list comprehension.
List comprehension is a way to create a new list based on an existing list.
Here is how you would get all indices of each occurrence of the string “Python”, using list comprehension:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = [index for (index, item) in enumerate(programming_languages) if item == "Python"]
print(python_indices)
#[1, 3, 5]
With the enumerate()
function you can store the indices of the items that meet the condition you set.
It first provides a pair (index, item
) for each element in the list (programming_languages
) that is passed as the argument to the function.
index
is for the index number of the list item and item
is for the list item itself.
Then, it acts as a counter which starts counting from 0
and increments each time the condition you set is met, selecting and moving the indices of the items that meet your criteria.
Paired with the list comprehension, a new list is created with all indices of the string “Python”.
Conclusion
And there you have it! You now know some of the ways to find the index of an item, and ways to find the indices of multiple occurrences of an item, in a list in Python.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Thanks for reading and happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Python index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the index of the first occurrence.
How to find the index of an element or items in a list
In this article, we will cover different examples to find the index, such as:
- Find the index of the element
- Working of the index() With Start and End Parameters
- Working of the index() With two Parameters only
- Index of the Element not Present in the List
- How to fix list index out of range
Syntax of index() Method
Syntax: list_name.index(element, start, end)
Parameters:
- element – The element whose lowest index will be returned.
- start (Optional) – The position from where the search begins.
- end (Optional) – The position from where the search ends.
Return: Returns the lowest index where the element appears.
Error: If any element which is not present is searched, it raises a ValueError.
Example 1: Find the index of the element
Finding index of ‘bat’ using index() on Python List list2
Python3
list2
=
[
'cat'
,
'bat'
,
'mat'
,
'cat'
,
'pet'
]
print
(list2.index(
'bat'
))
Output:
1
Example 2: Working of the index() With Start and End Parameters
In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position.
Python3
list1
=
[
1
,
2
,
3
,
4
,
1
,
1
,
1
,
4
,
5
]
print
(list1.index(
4
,
4
,
8
))
Output:
7
Example 3: Working of the index() With two Parameters only
In this example, we will see when we pass two arguments in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins.
list_name.index(element, start)
Python3
list1
=
[
6
,
8
,
5
,
6
,
1
,
2
]
print
(list1.index(
6
,
1
))
Output:
3
Example 4: Index of the Element not Present in the List
Python List index() raises ValueError, when the search element is not present inside the List.
Python3
list1
=
[
1
,
2
,
3
,
4
,
1
,
1
,
1
,
4
,
5
]
print
(list1.index(
10
))
Output:
Traceback (most recent call last): File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in print(list1.index(10)) ValueError: 10 is not in list
Example 5: How to fix list index out of range using Index()
Here we are going to create a list and then try to iterate the list using the constant values in for loops.
Python3
li
=
[
1
,
2
,
3
,
4
,
5
]
for
i
in
range
(
6
):
print
(li[i])
Output:
1 2 3 4 5 IndexError: list index out of range
Reason for the error: The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.
Solving this error without using len() or constant Value:
To solve this error we will take the index of the last value of the list and then add one, then it will become the exact value of length.
Python3
li
=
[
1
,
2
,
3
,
4
,
5
]
for
i
in
range
(li.index(li[
-
1
])
+
1
):
print
(li[i])
Last Updated :
17 Aug, 2022
Like Article
Save Article
Изучая программирование на Python, вы практически в самом начале знакомитесь со списками и различными операциями, которые можете выполнять над ними. В этой статье мы бы хотели рассказать об одной из таких операций над списками.
Представьте, что у вас есть список, состоящий из каких-то элементов, и вам нужно определить индекс элемента со значением x
. Сегодня мы рассмотрим, как узнать индекс определенного элемента списка в Python.
Но сначала давайте убедимся, что все понимают, что представляет из себя список.
Список в Python — это встроенный тип данных, который позволяет нам хранить множество различных значений, таких как числа, строки, объекты datetime
и так далее.
Важно отметить, что списки упорядочены. Это означает, что последовательность, в которой мы храним значения, важна.
Индексирование списка начинаются с нуля и заканчивается на длине списка минус один. Для получения более подробной информации о списках вы можете обратиться к статье «Списки в Python: полное руководство для начинающих».
Итак, давайте посмотрим на пример списка:
fruits = ["apple", "orange","grapes","guava"] print(type(fruits)) print(fruits[0]) print(fruits[1]) print(fruits[2]) # Результат: # <class 'list'> # apple # orange # grapes
Мы создали список из 4 элементов. Первый элемент в списке имеет нулевой индекс, второй элемент — индекс 1, третий элемент — индекс 2, а последний — 3.
Для списка получившихся фруктов fruits
допустимыми индексами являются 0, 1, 2 и 3. При этом длина списка равна 4 (в списке 4 элемента). Индекс последнего элемента равен длине списка (4) минус один, то есть как раз 3.
[python_ad_block]
Как определить индекс элемента списка в Python
Итак, как же определить индекс элемента в Python? Давайте представим, что у нас есть элемент списка и нам нужно узнать индекс или позицию этого элемента. Сделать это можно следующим образом:
print(fruits.index('orange')) # 1 print(fruits.index('guava')) # 3 print(fruits.index('banana')) # А здесь выскочит ValueError, потому что в списке нет значения banana
Списки Python предоставляют нам метод index()
, с помощью которого можно получить индекс первого вхождения элемента в список, как это показано выше.
Познакомиться с другими методами списков можно в статье «Методы списков Python».
Мы также можем заметить, что метод index()
вызовет ошибку VauleError
, если мы попытаемся определить индекс элемента, которого нет в исходном списке.
Для получения более подробной информации о методе index()
загляните в официальную документацию.
Базовый синтаксис метода index() выглядит так:
list_var.index(item)
,
где list_var
— это исходный список, item
— искомый элемент.
Мы также можем указать подсписок для поиска, и синтаксис для этого будет выглядеть следующим образом:
list_var.index(item, start_index_of_sublist, end_index_of_sublist)
Здесь добавляются два аргумента: start_index_of_sublist
и end_index_of_sublist
. Тут всё просто. start_index_of_sublist
обозначает, с какого элемента списка мы хотим начать поиск, а end_index_of_sublist
, соответственно, на каком элементе (не включительно) мы хотим закончить.
Чтобы проиллюстрировать это для лучшего понимания, давайте рассмотрим следующий пример.
Предположим, у нас есть список book_shelf_genres
, где индекс означает номер полки (индексация начинается с нуля). У нас много полок, среди них есть и полки с учебниками по математике.
Мы хотим узнать, где стоят учебники по математике, но не вообще, а после четвертой полки. Для этого напишем следующую программу:
book_shelf_genres = ["Fiction", "Math", "Non-fiction", "History", "Math", "Coding", "Cooking", "Math"] print(book_shelf_genres.index("Math")) # Результат: # 1
Здесь мы видим проблему. Использование просто метода index()
без дополнительных аргументов выдаст первое вхождение элемента в список, но мы хотим знать индекс значения «Math»
после полки 4.
Для этого мы используем метод index()
и указываем подсписок для поиска. Подсписок начинается с индекса 5 до конца списка book_shelf_genres
, как это показано во фрагменте кода ниже:
print(book_shelf_genres.index("Math", 5)) # Результат: # 7
Обратите внимание, что указывать конечный индекс подсписка необязательно.
Чтобы вывести индекс элемента «Math»
после полки номер 1 и перед полкой номер 5, мы просто напишем следующее:
print(book_shelf_genres.index("Math", 2, 5)) # Результат: # 4
Как найти индексы всех вхождений элемента в списке
А что, если искомое значение встречается в списке несколько раз и мы хотим узнать индексы всех этих элементов? Метод index()
выдаст нам индекс только первого вхождения.
В этом случае мы можем использовать генератор списков:
book_shelf_genres = ["Fiction", "Math", "Non-fiction", "History", "Math", "Coding", "Cooking", "Math"] indices = [i for i in range(0, len(book_shelf_genres)) if book_shelf_genres[i]=="Math"] print(indices) # Результат: # [1, 4, 7]
В этом фрагменте кода мы перебираем индексы списка в цикле for и при помощи range(). Далее мы проверяем значение элемента под каждым индексом на равенство «Math
«. Если значение элемента — «Math
«, мы сохраняем значение индекса в списке.
Все это делается при помощи генератора списка, который позволяет нам перебирать список и выполнять некоторые операции с его элементами. В нашем случае мы принимаем решения на основе значения элемента списка, а в итоге создаем новый список.
Подробнее про генераторы списков можно почитать в статье «Генераторы списков в Python для начинающих».
Благодаря генератору мы получили все номера полок, на которых стоят книги по математике.
Как найти индекс элемента в списке списков
Теперь представьте ситуацию, что у вас есть вложенный список, то есть список, состоящий из других списков. И ваша задача — определить индекс искомого элемента для каждого из подсписков. Сделать это можно следующим образом:
programming_languages = [["C","C++","Java"], ["Python","Rust","R"], ["JavaScript","Prolog","Python"]] indices = [(i, x.index("Python")) for i, x in enumerate(programming_languages) if "Python" in x] print(indices) # Результат: # [(1, 0), (2, 2)]
Здесь мы используем генератор списков и метод index()
, чтобы найти индексы элементов со значением «Python»
в каждом из имеющихся подсписков. Что же делает этот код?
Мы передаем список programming_languages
методу enumerate()
, который просматривает каждый элемент в списке и возвращает кортеж, содержащий индекс и значение элемента списка.
Каждый элемент в списке programming_languages
также является списком. Оператор in
проверяет, присутствует ли элемент «Python»
в этом списке. Если да — мы сохраняем индекс подсписка и индекс элемента «Python»
внутри подсписка в виде кортежа.
Результатом программы, как вы можете видеть, является список кортежей. Первый элемент кортежа — индекс подсписка, а второй — индекс искомого элемента в этом подсписке.
Таким образом, (1,0)
означает, что подсписок с индексом 1 списка programming_languages
имеет элемент «Python»
, который расположен по индексу 0. То есть, говоря простыми словами, второй подсписок содержит искомый элемент и этот элемент стоит на первом месте. Не забываем, что в Python индексация идет с нуля.
Как искать индекс элемента, которого, возможно, нет в списке
Бывает, нужно получить индекс элемента, но мы не уверены, есть ли он в списке.
Если попытаться получить индекс элемента, которого нет в списке, метод index()
вызовет ошибку ValueError
. При отсутствии обработки исключений ValueError
вызовет аварийное завершение программы. Такой исход явно не является хорошим и с ним нужно что-то сделать.
Вот два способа, с помощью которых мы можем избежать такой ситуации:
books = ["Cracking the Coding Interview", "Clean Code", "The Pragmatic Programmer"] ind = books.index("The Pragmatic Programmer") if "The Pragmatic Programmer" in books else -1 print(ind) # Результат: # 2
Один из способов — проверить с помощью оператора in
, есть ли элемент в списке. Оператор in
имеет следующий синтаксис:
var in iterable
Итерируемый объект — iterable
— может быть списком, кортежем, множеством, строкой или словарем. Если var
существует как элемент в iterable
, оператор in
возвращает значение True
. В противном случае он возвращает False
.
Это идеально подходит для решения нашей проблемы. Мы просто проверим, есть ли элемент в списке, и вызовем метод index()
только если элемент существует. Это гарантирует, что метод index()
не вызовет нам ошибку ValueError
.
Но если мы не хотим тратить время на проверку наличия элемента в списке (это особенно актуально для больших списков), мы можем обработать ValueError
следующим образом:
books = ["Cracking the Coding Interview", "Clean Code", "The Pragmatic Programmer"] try: ind = books.index("Design Patterns") except ValueError: ind = -1 print(ind) # Результат: # -1
Здесь мы применили конструкцию try-except
для обработки ошибок. Программа попытается выполнить блок, стоящий после слова try
. Если это приведет к ошибке ValueError
, то она выполнит блок после ключевого слова except
. Подробнее про обработку исключений с помощью try-except
можно почитать в статье «Обрабатываем исключения в Python: try и except».
Заключение
Итак, мы разобрали как определить индекс элемента списка в Python. Теперь вы знаете, как это сделать с помощью метода index()
и генератора списков.
Мы также разобрали, как использовать метод index()
для вложенных списков и как найти каждое вхождение элемента в списке. Кроме того, мы рассмотрели ситуацию, когда нужно найти индекс элемента, которого, возможно, нет в списке.
Мы надеемся, что данная статья была для вас полезной. Успехов в написании кода!
Больше 50 задач по Python c решением и дискуссией между подписчиками можно посмотреть тут
Перевод статьи «Python Index – How to Find the Index of an Element in a List».
In this tutorial, you’ll learn how to use the Python list index method to find the index (or indices) of an item in a list. The method replicates the behavior of the indexOf() method in many other languages, such as JavaScript. Being able to work with Python lists is an important skill for a Pythonista of any skill level. We’ll cover how to find a single item, multiple items, and items meetings a single condition.
By the end of this tutorial, you’ll have learned:
- How the Python
list.index()
method works - How to find a single item’s index in a list
- How to find the indices of all items in a list
- How to find the indices of items matching a condition
- How to use alternative methods like list comprehensions to find the index of an item in a list
Python List Index Method Explained
The Python list.index()
method returns the index of the item specified in the list. The method will return only the first instance of that item. It will raise a ValueError
is that item is not present in the list.
Let’s take a look at the syntax of the index()
method:
# The list.index() Method Explained
list.index(
element, # The element to search for
start, # The index to start searching at
end # The index to end searching at
)
Let’s break these parameters down a little further:
element=
represents the element to be search for in the liststart=
is an optional parameter that indicates which index position to start searching fromend=
is an optional parameter that indicates which index position to search up to
The method returns the index of the given element if it exists. Keep in mind, it will only return the first index. Additionally, if an item doesn’t exist, a ValueError
will be raised.
In the next section, you’ll learn how to use the .index()
method.
Find the Index Position of an Item in a Python List
Let’s take a look at how the Python list.index()
method works. In this example, we’ll search for the index position of an item we know is in the list.
Let’s imagine we have a list of the websites we open up in the morning and we want to know at which points we opened 'datagy'
.
# Finding the index of an item in a list
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('datagy'))
# Returns: 0
We can see that the word 'datagy'
was in the first index position. We can see that the word 'twitter'
appears more than once in the list. In the next section, you’ll learn how to find every index position of an item.
Finding All Indices of an Item in a Python List
In the section above, you learned that the list.index()
method only returns the first index of an item in a list. In many cases, however, you’ll want to know the index positions of all items in a list that match a condition.
Unfortunately, Python doesn’t provide an easy method to do this. However, we can make use of incredibly versatile enumerate()
function and a for-loop to do this. The enumerate function iterates of an item and returns both the index position and the value.
Let’s see how we can find all the index positions of an item in a list using a for loop and the enumerate()
function:
# Finding all indices of an item in a list
def find_indices(search_list, search_item):
indices = []
for (index, item) in enumerate(search_list):
if item == search_item:
indices.append(index)
return indices
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))
# Returns: [1, 3]
Let’s break down what we did here:
- We defined a function,
find_indices()
, that takes two arguments: the list to search and the item to find - The function instantiates an empty list to store any index position it finds
- The function then loops over the index and item in the result of the
enumerate()
function - For each item, the function evaludates if the item is equal to the search term. If it is, the index is appended to the list
- Finally, this list is returned
We can also shorten this list for a more compact version by using a Python list comprehension. Let’s see what this looks like:
# A shortened function to return all indices of an item in a list
def find_indices(search_list, search_item):
return [index for (index, item) in enumerate(search_list) if item == search_item]
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))
# Returns: [1, 3]
One of the perks of both these functions is that when an item doesn’t exist in a list, the function will simply return an empty list, rather than raising an error.
Find the Last Index Position of an Item in a Python List
In this section, you’ll learn how to find the last index position of an item in a list. There are different ways to approach this. Depending on the size of your list, you may want to choose one approach over the other.
For smaller lists, let’s use this simpler approach:
# Finding the last index position of an item in a list
def find_last_index(search_list, search_item):
return len(search_list) - 1 - search_list[::-1].index(search_item)
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_last_index(a_list, 'twitter'))
# Returns: 3
In this approach, the function subtracts the following values:
len(search_list)
returns the length of the list1
, since indices start at0
- The
.index()
of the reversed list
There are two main problems with this approach:
- If an item doesn’t exist, an
ValueError
will be raised - The function makes a copy of the list. This can be fine for smaller lists, but for larger lists this approach may be computationally expensive.
Let’s take a look at another approach that loops over the list in reverse order. This saves the trouble of duplicating the list:
# A less simple, but more memory efficient way of finding the last index of an item
def find_last_index(search_list, search_item):
i = len(search_list) - 1
while i >= 0:
if search_list[i] == search_item:
return i
else:
i -= 1
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_last_index(a_list, 'twitter'))
# Returns: 3
In the example above we loop over the list in reverse, by starting at the last index. We then evaluate if that item is equal to the search term. If it is we return the index position and the loop ends. Otherwise, we decrement the value by 1 using the augmented assignment operator.
Index of an Element Not Present in a Python List
By default, the Python list.index()
method will raise a ValueError
if an item is not present in a list. Let’s see what this looks like. We’ll search for the term 'pinterest'
in our list:
# Searching for an item that doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('pinterest'))
# Raises: ValueError: 'pinterest' is not in list
When Python raises this error, the entire program stops. We can work around this by nesting it in a try-except
block.
Let’s see how we can handle this error:
# Handling an error when an item doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
try:
print(a_list.index('pinterest'))
except ValueError:
print("Item doesn't exist!")
# Returns: Item doesn't exist!
Working with List Index Method Parameters
The Python list.index()
method also provides two additional parameters, start=
and stop=
. These parameters, respectively, indicate the positions at which to start and stop searching.
Let’s say that we wanted to start searching at the second index and stop at the sixth, we could write:
# Using Start and Stop Parameters in list.index()
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('twitter', 2, 6))
# Returns: 3
By instructing the method to start at index 2
, the method skips over the first instance of the string 'twitter'
.
Finding All Indices of Items Matching a Condition
In this final section, we’ll explore how to find the index positions of all items that match a condition. Let’s say, for example, that we wanted to find all the index positions of items that contain the letter 'y'
. We could use emulate the approach above where we find the index position of all items. However, we’ll add in an extra condition to our check:
# Finding Indices of Items Matching a Condition
def find_indices(search_list, search_item):
return [index for (index, item) in enumerate(search_list) if search_item in item]
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'y'))
# Returns:
# [0, 5]
The main difference in this function to the one shared above is that we evaluate on a more “fuzzy” condition.
Conclusion
In this tutorial, you learned how to use the index list method in Python. You learned how the method works and how to use it to find the index position of a search term. You also learned how to find the index positions of items that exist more than once, as well as finding the last index position of an item.
Finally, you learned how to handle errors when an item doesn’t exist as well as how to find the indices of items that match a condition.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Python Lists: A Complete Overview
- Python Zip Lists – Zip Two or More Lists in Python
- Python IndexError: List Index Out of Range Error Explained
- Python List Index: Official Documentation