Как найти индекс строки в списке

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.

Метод index() возвращает индекс указанного элемента в списке.

Синтаксис метода в Python:

list.index(element, start, end)

Список параметров

Метод в Python может принимать не более трех аргументов:

  • element – элемент для поиска;
  • start (необязательно) – начать поиск с этого индекса;
  • end (необязательно) – искать элемент до этого индекса.

Возвращаемое значение из списка

  • Метод возвращает индекс данного элемента в списке.
  • Если элемент не найден, возникает исключение ValueError.

Примечание: Команда возвращает только первое вхождение соответствующего элемента.

Пример 1: Найти индекс элемента

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)

# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')

print('The index of i:', index)

Выход

The index of e: 1
The index of i: 2

Пример 2: Указатель элемента, отсутствующего в списке

# vowels list
vowels = ['a', 'e', 'i', 'o', 'u']

# index of'p' is vowels
index = vowels.index('p')
print('The index of p:', index)

Выход

ValueError: 'p' is not in list

Пример 3: Работа с параметрами начала и конца

# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']

# index of 'i' in alphabets
index = alphabets.index('e')   # 2
print('The index of e:', index)

# 'i' after the 4th index is searched
index = alphabets.index('i', 4)   # 6
print('The index of i:', index)

# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5)   # Error!
print('The index of i:', index)

Выход

The index of e: 1
The index of i: 6
Traceback (most recent call last):
  File "*lt;string>", line 13, in 
ValueError: 'i' is not in list

336-559cookie-checkФункция index() в Python

Изучая программирование на 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».

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 Index – How to Find the Index of an Element in a List

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:

image-173

fruits = ["apple", "orange","grapes","guava"]
type(fruits)
print(fruits[0])
print(fruits[1])
print(fruits[2])

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.

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.

index = fruits.index('orange')
#The value of index is 1

index = fruits.index('guava')
#The value of index is 3

index = fruits.index('banana')
#This raises a ValueError as banana is not present in list

image-174

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:

list_var.index(item)

We can also specify a sublist in which to search, and the syntax for that is:

list_var.index(item, start_index_of_sublist, end_index_of_sublist)

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.

book_shelf_genres = ["Fiction", "Math", "Non-fiction", "History", "Math", "Coding", "Cooking", "Math"]
index = book_shelf_genres.index("Math")
#The value of index is 1

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

index = book_shelf_genres.index("Math", 5)
#The value of index is 7

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:

index = book_shelf_genres.index("Math", 2, 5)
#The value of index is 4

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:

book_shelf_genres = ["Fiction", "Math", "Non-fiction", "History", "Math", "Coding", 
                     "Cooking", "Math"]

[i for i in range(0, len(book_shelf_genres)) if book_shelf_genres[i]=="Math"]

image-229

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

programming_languages = [["C","C++","Java"],["Python","Rust","R"],
                         ["JavaScript","Prolog","Python"]]

[ (i, x.index("Python")) for i, x in enumerate(programming_languages) if "Python" in x ]

image-230

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:

books = ["Cracking the Coding Interview", "Clean Code", "The Pragmatic Programmer"]
ind = books.index("The Pragmatic Programmer") if "The Pragmatic Programmer" in books else -1
                                            

image-180

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

var in iterable

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:

books = ["Cracking the Coding Interview", "Clean Code", "The Pragmatic Programmer"]
try:
    ind = books.index("Design Patterns")
except ValueError:
    ind = -1
ind

image-181

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!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Добавить комментарий