Как найти индекс элемента в списке

от admin

Python Index – How to Find the Index of an Element in a List

Suchandra Datta

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

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.

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:

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:

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

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:

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

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:

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!

Найти индекс элемента в списке Python

В этом посте мы обсудим, как найти индекс элемента в списке Python.

С использованием index() функция

Предпочтительный идиоматический способ найти индекс элемента в списке — использовать index() функция:

The index() Функция возвращает индекс первого вхождения заданного элемента в список. Однако он повышает ValueError если элемент не найден в списке. Вы можете справиться с этим следующими способами:

⮚ In оператор

Идея состоит в том, чтобы проверить наличие элемента в списке с помощью оператора in перед вызовом функции. index() функция:

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 ?

Mateen Ulhaq's user avatar

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.

Читать:
Stdafx h как подключить

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() :

TerryA's user avatar

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:

tanzil's user avatar

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.

Peter Mortensen's user avatar

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?

Peter Badida's user avatar

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

Чтобы найти индекс первого вхождения элемента в данном списке в Python, вы можете использовать метод index() класса List с элементом, переданным в качестве аргумента.

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

Вы также можете указать начальную и конечную позиции списка, где должен происходить поиск в списке.

Ниже приводится синтаксис функции index() с начальной и конечной позициями.

Параметр start не является обязательным. Если вы указываете значение для начала, то конец указывать необязательно.

Мы рассмотрим примеры, где подробно рассмотрим каждый из этих сценариев.

Нахождение индекса элемента в Python

Пример 1

В следующем примере мы взяли список с числами. С помощью метода index() найдем индекс пункта 8 в списке.

Элемент находится на 3-й позиции, поэтому функция mylist.index() вернула 2.

Пример 2

В следующем примере мы взяли список с числами. С помощью метода index() найдем индекс пункта 8 в списке, а также пропустим начало и конец. Функция рассматривает элементы в списке, начиная с начального индекса до конечной позиции в mylist.

Пример 3: если элемент имеет несколько вхождений в списке

Список в Python может содержать несколько экземпляров элемента. В таких случаях возвращается только индекс первого появления указанного элемента в списке.

Элемент 52 присутствует два раза, но метод index() возвращает только индекс первого вхождения.

Давайте разберемся, как работает index(). Функция просматривает список с самого начала. Когда элемент соответствует аргументу, функция возвращает этот индекс. Более поздние случаи игнорируются.

Пример 4: если элемент отсутствует

Если элемент, который мы ищем в списке, отсутствует, вы получите ValueError.

В следующей программе мы взяли список и попытаемся найти индекс элемента, которого нет в списке.

Поскольку index() может вызывать ValueError, используйте Try-Except. В следующем примере мы узнаем, как использовать инструкцию try-except для обработки этой ValueError.

Элемент, индекс которого мы пытаемся найти, отсутствует в списке. Следовательно, mylist.index (item) выдает ValueError, после блок перехватывает эту ошибку, и соответствующий блок выполняется.

Заключение

В этом руководстве по Python мы узнали, как найти индекс элемента в списке с помощью подробных примеров.

Похожие статьи