Список
Список — это непрерывная динамическая коллекция элементов. Каждому элементу списка присваивается порядковый номер — его индекс. Первый индекс равен нулю, второй — единице и так далее. Основные операции для работы со списками — это индексирование, срезы, добавление и удаление элементов, а также проверка на наличие элемента в последовательности.
Создание пустого списка выглядит так:
Создадим список, состоящий из нескольких чисел:
numbers = [ 40 , 20 , 90 , 11 , 5 ]
Настало время строковых переменных:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
Не будем забывать и о дробях:
fractions = [ 3.14 , 2.72 , 1.41 , 1.73 , 17.9 ]
Мы можем создать список, состоящий из различных типов данных:
values = [ 3.14 , 10 , ‘Hello world!’ , False, ‘Python is the best’ ]
И такое возможно (⊙_⊙)
list_of_lists = [[ 2 , 4 , 0 ], [ 11 , 2 , 10 ], [ 0 , 19 , 27 ]]
Индексирование
Что же такое индексирование? Это загадочное слово обозначает операцию обращения к элементу по его порядковому номеру ( ( ・ω・)ア напоминаю, что нумерация начинается с нуля). Проиллюстрируем это на примере:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ 0 ])
print (fruits[ 1 ])
print (fruits[ 4 ])
Списки в Python являются изменяемым типом данных. Мы можем изменять содержимое каждой из ячеек:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
fruits[ 0 ] = ‘Watermelon’
fruits[ 3 ] = ‘Lemon’
print (fruits)
>>> [ ‘Watermelon’ , ‘Grape’ , ‘Peach’ , ‘Lemon’ , ‘Orange’ ]
Индексирование работает и в обратную сторону. Как такое возможно? Всё просто, мы обращаемся к элементу списка по отрицательному индексу. Индекс с номером -1 дает нам доступ к последнему элементу, -2 к предпоследнему и так далее.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ -1 ])
print (fruits[ -2 ])
print (fruits[ -3 ])
print (fruits[ -4 ])
Создание списка с помощью list()
Переходим к способам создания списка. Самый простой из них был приведен выше. Еще раз для закрепления:
А есть еще способы? Да, есть. Один из них — создание списка с помощью функции list() В неё мы можем передать любой итерируемый объект (да-да, тот самый по которому можно запустить цикл (• ᵕ •) )
Рассмотрим несколько примеров:
letters = list ( ‘abcdef’ )
numbers = list ( range ( 10 ))
even_numbers = list ( range ( 0 , 10 , 2 ))
print (letters)
print (numbers)
print (even_numbers)
>>> [ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’
>>> [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> [ 0 , 2 , 4 , 6 , 8 ]
Длина списка
С созданием списка вроде разобрались. Следующий вопрос: как узнать длину списка? Можно, конечно, просто посчитать количество элементов. (⊙_⊙) Но есть способ получше! Функция len() возвращает длину любой итерируемой переменной, переменной, по которой можно запустить цикл. Рассмотрим пример:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print ( len (fruits))
numbers = [ 40 , 20 , 90 ]
print ( len (numbers))
«. любой итерируемой», а это значит:
string = ‘Hello world’
print ( len (string))
# 11
print ( len ( range ( 10 ))
Срезы
В начале статьи что-то говорилось о «срезах». Давайте разберем подробнее, что это такое. Срезом называется некоторая подпоследовательность. Принцип действия срезов очень прост: мы «отрезаем» кусок от исходной последовательности элемента, не меняя её при этом. Я сказал «последовательность», а не «список», потому что срезы работают и с другими итерируемыми типами данных, например, со строками.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
part_of_fruits = fruits[ 0 :3]
print (part_of_fruits)
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ ]
Детально рассмотрим синтаксис срезов:
итерируемая_переменная[начальный_индекс:конечный_индекс — 1 :длина_шага]
Обращаю ваше внимание, что мы делаем срез от начального индекса до конечного индекса — 1. То есть i = начальный_индекс и i = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ 0 :1])
# Если начальный индекс равен 0, то его можно опустить
print (fruits[: 2 ])
print (fruits[: 3 ])
print (fruits[: 4 ])
print (fruits[: 5 ])
# Если конечный индекс равен длине списка, то его тоже можно опустить
print (fruits[: len (fruits)])
print (fruits[::])
>>> [ ‘Apple’ ]
>>> [ ‘Apple’ , ‘Grape’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
Самое время понять, что делает третий параметр среза — длина шага!
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[:: 2 ])
print (fruits[:: 3 ])
# Длина шага тоже может быть отрицательной!
print (fruits[:: -1 ])
print (fruits[ 4 :2: -1 ])
print (fruits[ 3 :1: -1 ])
>>> [ ‘Apple’ , ‘Peach’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Banan’ ]
>>> [ ‘Orange’ , ‘Banan’ , ‘Peach’ , ‘Grape’ , ‘Apple’ ]
>>> [ ‘Orange’ , ‘Banan’ ]
>>> [ ‘Banan’ , ‘Peach’ ]
А теперь вспоминаем всё, что мы знаем о циклах. В Python их целых два! Цикл for и цикл while Нас интересует цикл for, с его помощью мы можем перебирать значения и индексы наших последовательностей. Начнем с перебора значений:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
f or fruit in fruits:
print (fruit, end = ‘ ‘ )
>>> Apple Grape Peach Banan Orange
Выглядит несложно, правда? В переменную fruit объявленную в цикле по очереди записываются значения всех элементов списка fruits
А что там с перебором индексов?
f or index in range ( len (fruits)):
print (fruits[index], end = ‘ ‘ )
Этот пример гораздо интереснее предыдущего! Что же здесь происходит? Для начала разберемся, что делает функция range(len(fruits))
Мы с вами знаем, что функция len() возвращает длину списка, а range() генерирует диапазон целых чисел от 0 до len()-1.
Сложив 2+2, мы получим, что переменная index принимает значения в диапазоне от 0 до len()-1. Идем дальше, fruits[index] — это обращение по индексу к элементу с индексом index списка fruits. А так как переменная index принимает значения всех индексов списка fruits, то в цикле мы переберем значения всех элементов нашего списка!
Операция in
С помощью in мы можем проверить наличие элемента в списке, строке и любой другой итерируемой переменной.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
if ‘Apple’ in fruits:
print ( ‘В списке есть элемент Apple’ )
>>> В списке есть элемент Apple
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
if ‘Lemon’ in fruits:
print ( ‘В списке есть элемент Lemon’ )
else :’
print ( ‘В списке НЕТ элемента Lemon’ )
>>> В списке НЕТ элемента Lemon
Приведу более сложный пример:
all_fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
my_favorite_fruits = [ ‘Apple’ , ‘Banan’ , ‘Orange’ ]
f or item in all_fruits:
if item in my_favorite_fruits:
print (item + ‘ is my favorite fruit’ )
else :
print ( ‘I do not like ‘ + item)
>>> Apple is my favorite fruit
>>> I do not like Grape
>>> I do not like Peach
>>> Banan is my favorite fruit
>>> Orange is my favorite fruit
Методы для работы со списками
Начнем с метода append(), который добавляет элемент в конец списка:
# Создаем список, состоящий из четных чисел от 0 до 8 включительно
numbers = list ( range ( 0 ,10, 2 ))
# Добавляем число 200 в конец списка
numbers. append ( 200 )
numbers. append ( 1 )
numbers. append ( 2 )
numbers. append ( 3 )
print (numbers)
>>> [ 0 , 2 , 4 , 6 , 8 , 200 , 1 , 2 , 3 ]
Мы можем передавать методу append() абсолютно любые значения:
all_types = [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. append ( 1024 )
all_types. append ( ‘Hello world!’ )
all_types. append ([ 1 , 2 , 3 ])
print (all_types)
>>> [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ], 1024 , ‘Hello world!’ , [ 1 , 2 , 3 ]]
Метод append() отлично выполняет свою функцию. Но, что делать, если нам нужно добавить элемент в середину списка? Это умеет метод insert(). Он добавляет элемент в список на произвольную позицию. insert() принимает в качестве первого аргумента позицию, на которую нужно вставить элемент, а вторым — сам элемент.
# Создадим список чисел от 0 до 9
numbers = list ( range ( 10 ))
# Добавление элемента 999 на позицию с индексом 0
numbers. insert ( 0 , 999 )
print (numbers) # первый print
numbers. insert ( 2 , 1024 )
print (numbers) # второй print
numbers. insert ( 5 , ‘Засланная строка-шпион’ )
print (numbers) # третий print
>>> [ 999 , 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # первый print
>>> [ 999 , 0 , 1024 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # второй print
>>> [ 999 , 0 , 1024 , 1 , 2 , ‘Засланная строка-шпион’ , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # третий print
Отлично! Добавлять элементы в список мы научились, осталось понять, как их из него удалять. Метод pop() удаляет элемент из списка по его индексу:
numbers = list ( range ( 10 ))
print (numbers) # 1
# Удаляем первый элемент
numbers. pop ( 0 )
print (numbers) # 2
numbers. pop ( 0 )
print (numbers) # 3
numbers. pop ( 2 )
print (numbers) # 4
# Чтобы удалить последний элемент, вызовем метод pop без аргументов
numbers. pop ()
print (numbers) # 5
numbers. pop ()
print (numbers) # 6
>>> [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 1
>>> [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 2
>>> [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 3
>>> [ 2 , 3 , 5 , 6 , 7 , 8 , 9 ] # 4
>>> [ 2 , 3 , 5 , 6 , 7 , 8 ] # 5
>>> [ 2 , 3 , 5 , 6 , 7 ] # 6
Теперь мы знаем, как удалять элемент из списка по его индексу. Но что, если мы не знаем индекса элемента, но знаем его значение? Для такого случая у нас есть метод remove(), который удаляет первый найденный по значению элемент в списке.
all_types = [ 10 , ‘Python’ , 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. remove ( 3.14 )
print (all_types) # 1
all_types. remove ( 10 )
print (all_types) # 2
all_types. remove ( ‘Python’ )
print (all_types) # 3
>>> [ 10 , ‘Python’ , 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 1
>>> [ ‘Python’ , 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 2
>>> [ 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 3
А сейчас немного посчитаем, посчитаем элементы списка с помощью метода count()
numbers = [ 100 , 100 , 100 , 200 , 200 , 500 , 500 , 500 , 500 , 500 , 999 ]
print (numbers. count ( 100 )) # 1
print (numbers. count ( 200 )) # 2
print (numbers. count ( 500 )) # 3
print (numbers. count ( 999 )) # 4
В программировании, как и в жизни, проще работать с упорядоченными данными, в них легче ориентироваться и что-либо искать. Метод sort() сортирует список по возрастанию значений его элементов.
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. sort ()
print (numbers) # 1
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits) # 2
>>> [ 2 , 3 , 9 , 11 , 78 , 100 , 567 , 1024 ] # 1
>>> [ ‘Apple’ , ‘Banan’ , ‘Grape’ , ‘Orange’ , ‘Peach’ ] # 2
Мы можем изменять порядок сортировки с помощью параметра reverse. По умолчанию этот параметр равен False
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits) # 1
fruits. sort (reverse = True)
print (fruits) # 2
>>> [ ‘Apple’ , ‘Banan’ , ‘Grape’ , ‘Orange’ , ‘Peach’ ] # 1
>>> [ ‘Peach’ , ‘Orange’ , ‘Grape’ , ‘Banan’ , ‘Apple’ ] # 2
Иногда нам нужно перевернуть список, не спрашивайте меня зачем. Для этого в самом лучшем языке программирования на этой планете JavaScr..Python есть метод reverse():
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. reverse ()
print (numbers) # 1
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. reverse ()
print (fruits) # 2
>>> [ 78 , 567 , 1024 , 3 , 9 , 11 , 2 , 100 ] # 1
>>> [ ‘Apple’ , ‘Banan’ , ‘Peach’ , ‘Grape’ , ‘Orange’ ] # 2
Допустим, у нас есть два списка и нам нужно их объединить. Программисты на C++ cразу же кинулись писать циклы for, но мы пишем на python, а в python у списков есть полезный метод extend(). Этот метод вызывается для одного списка, а в качестве аргумента ему передается другой список, extend() записывает в конец первого из них начало второго:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. extend (vegetables)
print (fruits)
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
В природе существует специальный метод для очистки списка — clear()
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. clear ()
vegetables. clear ()
print (fruits)
print (vegetables)
Осталось совсем чуть-чуть всего лишь пара методов, так что делаем последний рывок! Метод index() возвращает индекс элемента. Работает это так: вы передаете в качестве аргумента в index() значение элемента, а метод возвращает его индекс:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
print (fruits. index ( ‘Apple’ ))
print (fruits. index ( ‘Banana’ ))
print (fruits. index ( ‘Grape’ ))
Финишная прямая! Метод copy(), только не падайте, копирует список и возвращает его брата-близнеца. Вообще, копирование списков — это тема достаточно интересная, давайте рассмотрим её по-подробнее.
Во-первых, если мы просто присвоим уже существующий список новой переменной, то на первый взгляд всё выглядит неплохо:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
print (fruits)
print (new_fruits)
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
Но есть одно маленькое «НО»:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
fruits. pop ()
print (fruits)
print (new_fruits)
# Внезапно, из списка new_fruits исчез последний элемент
>>> [ ‘Banana’ , ‘Apple’ ]
>>> [ ‘Banana’ , ‘Apple’ ]
При прямом присваивании списков копирования не происходит. Обе переменные начинают ссылаться на один и тот же список! То есть если мы изменим один из них, то изменится и другой. Что же тогда делать? Пользоваться методом copy(), конечно:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits. copy ()
fruits. pop ()
print (fruits)
print (new_fruits)
>>> [ ‘Banana’ , ‘Apple’ ]
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
Отлично! Но что если у нас список в списке? Скопируется ли внутренний список с помощью метода copy() — нет:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ , ‘Peach’ ]]
new_fruits = fruits. copy ()
fruits[ -1 ]. pop ()
print (fruits) # 1
print (new_fruits) # 2
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ ]] # 1
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ ]] # 2
Решение задач
1. Создайте список из 10 четных чисел и выведите его с помощью цикла for
2. Создайте список из 5 элементов. Сделайте срез от второго индекса до четвертого
3. Создайте пустой список и добавьте в него 10 случайных чисел и выведите их. В данной задаче нужно использовать функцию randint.
from random import randint
n = randint ( 1 , 10 ) # Случайное число от 1 до 10
4. Удалите все элементы из списка, созданного в задании 3
5. Создайте список из введенной пользователем строки и удалите из него символы ‘a’, ‘e’, ‘o’
6. Даны два списка, удалите все элементы первого списка из второго
a = [ 1 , 3 , 4 , 5 ]
b = [ 4 , 5 , 6 , 7 ]
# Вывод
>>> [ 6 , 7 ]
7. Создайте список из случайных чисел и найдите наибольший элемент в нем.
8. Найдите наименьший элемент в списке из задания 7
9. Найдите сумму элементов списка из задания 7
10. Найдите среднее арифметическое элементов списка из задания 7
Сложные задачи
1. Создайте список из случайных чисел. Найдите номер его последнего локального максимума (локальный максимум — это элемент, который больше любого из своих соседей).
2. Создайте список из случайных чисел. Найдите максимальное количество его одинаковых элементов.
3. Создайте список из случайных чисел. Найдите второй максимум.
a = [ 1 , 2 , 3 ] # Первый максимум == 3, второй == 2
4. Создайте список из случайных чисел. Найдите количество различных элементов в нем.
Python Index – How to Find the Index of an Element in a List

Suchandra Datta

When you’re learning to code, you eventually learn about lists and the different operations you can perform on them.
In this article, we’ll go through how you can find the index of a particular element which is stored in a list in Python.
What is a List in Python?
A list in Python is an in-built data type which allows us to store a bunch of different values, like numbers, strings, datetime objects and so on.
Lists are ordered, which means the sequence in which we store the values is important.
List indices start from zero and end at the length of the list minus one. For more detailed information on list data type, check out this comprehensive guide.
Let’s see an example of lists:

Here we created a list of 4 items, where we see that the first item in the list is at index zero, the second item is at index 1, the third item is at index 2, and so on.
For the fruits list, the valid list indices are 0, 1, 2 and 3.
How to Find the Index of Items in a List in Python
Let’s do the reverse. That is, given a list item, let’s find out the index or position of that item in the list.

Python lists provide us with the index method which allows us to get the index of the first occurrence of a list item, as shown above.
We can also see that the index method will raise a VauleError if we try to find the index of an item which does not exist in the list.
For greater detail on the index method, check out the official docs here.
The basic syntax of the index method is this:
We can also specify a sublist in which to search, and the syntax for that is:
To illustrate this further, let’s look at an example.
Suppose we have a book_shelf_genres list where the index signifies the shelf number. We have many shelves containing math books. Shelf numbers also start from zero. We want to know which shelf after shelf 4 has any math books.
We can see the problem here: using just index() will give the first occurrence of the item in the list – but we want to know the index of «Math» after shelf 4.
To do that, we use the index method and specify the sublist to search in. The sublist starts at index 5 until the end of the book_shelf_genres list, as shown in the code snippet below
Note that giving the end index of the sublist is optional. To find index of «Math» after shelf number 1 and before shelf number 5, we will simply do this:
How to Find the Index of a List Item with Multiple Occurrences in Python
What if we need to know the index of a list item which occurs multiple times in a list? The index method won’t give us every occurrence.
In this case, we can find the multiple occurrences using list comprehension as follows:

As shown in this code snippet, we loop over the indices of the list. At each index we check if the item at that index is Math or not. If it is Math then we store that index value in a list.
We do this entire process using list comprehension, which is just syntactic sugar that allows us to iterate over a list and perform some operation. In our case we are doing decision making based on the value of list item. Then we create a new list.
With this process, we now know all the shelf numbers which have math books on them.
How to Find the Index of List Items in a List of Lists in Python

Here we use list comprehension and the index method to find the index of «Python» in each of the sublists.
We pass the programming_languages list to the enumerate method which goes over each item in list and returns a tuple containing the index and item of the list at that index.
Each item in programming_languages list is also a list. The in operator then checks whether «Python» is present in this list or not. If present, we store the sublist index and index of «Python» inside the sublist as a tuple.
The output is a list of tuples. The first item in the tuple specifies the sublist index, and the second number specifies the index within the sublist.
So (1,0) means that the sublist at index 1 of the programming_languages list has the «Python» item at index 0.
How to Find the Index of a List Item that May Not Exist in a List in Python
In many cases, we will end up trying to get the index of an item but we are not sure if the item exists in the list or not.
If we have a piece of code which tries to get index of an item which isn’t present in the list, the index() method will raise a ValueError. In the absence of exception handling, this ValueError will cause abnormal program termination.
Here’s two ways in which we can avoid or handle this situation:

One way is to check using the «in» operator if the item exists in list or not. The in operator has the basic syntax of
where iterable could be a list, tuple, set, string or dictionary. If var exists as an item in the iterable, the in operator returns True. Else it returns False.
This is ideal for our case. We will simply check if an item exists in the list or not and only when it exists we will call index() method. This makes sure that the index() method doesn’t raise a ValueError.
If we don’t want to spend time checking if an item exists in the list or not, especially for large lists, we can handle the ValueError like this:

Wrapping up
Today we learnt how to find the index of an item in a list using the index() method.
We also saw how to use the index method over sublists, how to find the index of items in a list of lists, how to find every occurrence of an item in a list, and how to check for items in lists which may not be present.
I hope you found this article useful and an enjoyable read. Happy coding!
Finding the index of an item in a list
Given a list ["foo", "bar", "baz"] and an item in the list "bar" , how do I get its index 1 ?
![]()
44 Answers 44
See the documentation for the built-in .index() method of the list:
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Caveats
Linear time-complexity in list length
An index call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.
This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the start and end parameters can be used to narrow the search.
The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.
Only the index of the first match is returned
A call to index searches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed, index cannot solve the problem:
The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.
Raises an exception if there is no match
As noted in the documentation above, using .index will raise an exception if the searched-for value is not in the list:
If this is a concern, either explicitly check first using item in my_list , or handle the exception with try / except as appropriate.
The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.
The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate() :
The index() function only returns the first occurrence, while enumerate() returns all occurrences.
As a list comprehension:
Here’s also another small solution with itertools.count() (which is pretty much the same approach as enumerate):
This is more efficient for larger lists than using enumerate() :
![]()
To get all indexes:
index() returns the first index of value!
| index(. )
| L.index(value, [start, [stop]]) -> integer — return first index of value
A problem will arise if the element is not in the list. This function handles the issue:
![]()
You have to set a condition to check if the element you’re searching is in the list
If you want all indexes, then you can use NumPy:
It is clear, readable solution.
![]()
All of the proposed functions here reproduce inherent language behavior but obscure what’s going on.
Why write a function with exception handling if the language provides the methods to do what you want itself?
![]()
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:
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:
And use it like this:
And the downside of this is that you will probably have a check for if the returned value is or is not None:
More than one value in the list
If you could have more occurrences, you’ll not get complete information with list.index :
You might enumerate into a list comprehension the indexes:
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:
Better data munging with pandas
If you have pandas, you can easily get this information with a Series object:
A comparison check will return a series of booleans:
Pass that series of booleans to the series via subscript notation, and you get just the matching members:
If you want just the indexes, the index attribute returns a series of integers:
And if you want them in a list or tuple, just pass them to the constructor:
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:
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:
In Lib/http/cookiejar.py, seems to be used to get the next month:
In Lib/tarfile.py similar to distutils to get a slice up to an item:
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.
Python List Index: Find First, Last or All Occurrences

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
Table of Contents
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:
Let’s break these parameters down a little further:
- element= represents the element to be search for in the list
- start= is an optional parameter that indicates which index position to start searching from
- end= 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’ .
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:
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:
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:
In this approach, the function subtracts the following values:
- len(search_list) returns the length of the list
- 1 , since indices start at 0
- 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:
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:
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:
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:
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:
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.