Как найти индекс элемента по значению python

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.

Perhaps the two most efficient ways to find the last index:

def rindex(lst, value):
    lst.reverse()
    i = lst.index(value)
    lst.reverse()
    return len(lst) - i - 1
def rindex(lst, value):
    return len(lst) - operator.indexOf(reversed(lst), value) - 1

Both take only O(1) extra space and the two in-place reversals of the first solution are much faster than creating a reverse copy. Let’s compare it with the other solutions posted previously:

def rindex(lst, value):
    return len(lst) - lst[::-1].index(value) - 1

def rindex(lst, value):
    return len(lst) - next(i for i, val in enumerate(reversed(lst)) if val == value) - 1

Benchmark results, my solutions are the red and green ones:
unshuffled, full range

This is for searching a number in a list of a million numbers. The x-axis is for the location of the searched element: 0% means it’s at the start of the list, 100% means it’s at the end of the list. All solutions are fastest at location 100%, with the two reversed solutions taking pretty much no time for that, the double-reverse solution taking a little time, and the reverse-copy taking a lot of time.

A closer look at the right end:
unshuffled, tail part

At location 100%, the reverse-copy solution and the double-reverse solution spend all their time on the reversals (index() is instant), so we see that the two in-place reversals are about seven times as fast as creating the reverse copy.

The above was with lst = list(range(1_000_000, 2_000_001)), which pretty much creates the int objects sequentially in memory, which is extremely cache-friendly. Let’s do it again after shuffling the list with random.shuffle(lst) (probably less realistic, but interesting):

shuffled list, full range

shuffled list, tail part

All got a lot slower, as expected. The reverse-copy solution suffers the most, at 100% it now takes about 32 times (!) as long as the double-reverse solution. And the enumerate-solution is now second-fastest only after location 98%.

Overall I like the operator.indexOf solution best, as it’s the fastest one for the last half or quarter of all locations, which are perhaps the more interesting locations if you’re actually doing rindex for something. And it’s only a bit slower than the double-reverse solution in earlier locations.

All benchmarks done with CPython 3.9.0 64-bit on Windows 10 Pro 1903 64-bit.

Изучая программирование на 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 Find in List – How to Find the Index of an Item or Element in a List

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:

  1. An overview of lists in Python
    1. How indexing works
  2. Use the index() method to find the index of an item
    1.Use optional parameters with the index() method
  3. Get the indices of all occurrences of an item in a list
    1. Use a for-loop to get indices of all occurrences of an item in a list
    2. Use list comprehension and the enumerate() function to get indices of all occurrences of an item in a list

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

In this Python tutorial, we will learn how to find the index of elements in a list by using Python. Also, we will cover these topics.

  • Python find index of element in list closest to value
  • Python find index of element in list greater than
  • Python find index of element in list of lists
  • Python find index of element in list with condition
  • Python find index of item in list
  • Python find index of object in list by attribute
  • Python find index of item in list containing string
  • Python get index of element in list by value
  • Python find index of item in list without exception
  • Python find index of item in list case insensitive
  • Python get index of item in list while iterating
  • Python get index of item in list with default
  • Python get index of element in list if exists
  • Python find index of item in list regex
  • Python find position of item in a list
  • Python get index of max element in a list.
  • Python find index of smallest element in list
  • Find index of duplicate elements in list Python
  • Python find index of multiple elements in list
  • Python get index of element in list NumPy
  • Python find index of common elements in two lists
  • Python get index of item in list comprehension
  • In this Program, we will discuss how to find the index of element in a list by using Python.
  • In Python to get the index of item in list. we are going to use a method list.index() and this function will always return the index of a particular item in the list and this is a in-built() function in Python.
  • In Python lists are basically collection of items and each item has its unique positions and these positions are called as indexes. Now by using the list.index() function we are able to get the index of an item in a list.

Syntax:

Here is the Syntax of the index() method

list.index(
           element,
           start,
           end
          )
  • It consists of few Parameters
    • element: This parameter indicates that which element you would like to find.
    • start: It is a optional parameter and it will help you to start the search.
    • end: This parameter specifies if you provide ‘end’ argument then the search will end at the index.

Example:

Let’s take an example and check how to find the index of an element in a list

new_lis = [82, 64, 189, 920, 452, 701]

new_val = 920
result = new_lis.index(new_val)
print(result)

In the above code, we have created a list with integer numbers and then we will find the index of ‘920’ in the given list. To do this task first we create a variable ‘result’ and then assign a list.index() method to get the index value of that number.

Here is the Output of the following given code

Python find index of element in list
Python find an index of an element in a list

Read Square Root in Python

Get index of elements in a Python list

  • Here in this example, we are going to use the combination of a for-loop and append() method to get the index of elements in a Python list.
  • To get the index of an element in a list first, we will create a list ‘lis_1’ and now we want to get the index number of ‘193’ which is present in the list and now I want all the indexes with the number of ‘193’.

Source Code:

lis_1 = ['45', '92', '193', '193', '231', '190'] 

emp_lis = [] 
for m in range(0, len(lis_1)) : 
    if lis_1[m] == '193' : 
        emp_lis.append(m)
print("Index no of '193':", emp_lis)

Here is the implementation of the following given code

Python find index of element in list
Python find the index of an element in a list

As you can see in the Screenshot the element is present at 2 and 3 positions.

Read: How to concatenate all elements of list into string in Python

By using NumPy method

  • In this example, we have especially used the concept of a Python numpy array to get the index of an element in a list. So to do this task first we will create a list and then use the np.array() function to convert the list into an array. Now we want to get the index of ‘119’ number which is available in the list.
  • To do this we can apply the concept np.where() method and this function will help the user to select elements from the given array based on the condition.

Source Code:

import numpy as np

new_list = [56,829,992,119,734,567,890] 
arr = np.array(new_list)
result = np.where(arr == 119)[0]
print(result)

You can refer to the below Screenshot

Python find index of element in list
Python find the index of an element in a list

As you can see in the Screenshot the element ‘119’ is present at 3 positions.

This is how to use the NumPy method to get the index of elements in a Python list.

Also, check: Python find number in String

Python find index of element in list closest to value

  • Let us see how to find an index of elements in a list that is closest to value.
  • By using the min() method we can apply a key that searches the difference of each item with K, and this method will always return the item which having less number of difference.

Example:

new_lis = [21.34,15.4567,18.478,22.105,13.189]

b = min(range(len(new_lis)), key=lambda m: abs(new_lis[m]-17.6))
print(b)

Here is the Screenshot of the following given code

Python find index of element in list closest to value
Python find an index of the element in the list closest to value

Read: Remove non-ASCII characters Python

Python find index of element in list greater than

In this example, we will use a Python lambda function to equate with the given value at each index and then, filter out the given condition. This method actually sets the index value as 0 and specifies the first item greater than the value.

Example:

my_lis = [109,134,12,83,10]

new_output = list(filter(lambda m: m > 120, my_lis))[0]
print(my_lis.index(new_output))

In the above code first, we have initialized a list ‘my_lis’ and then used the filter+ lambda() function to get the index of elements in a list that is greater than ‘120’.

Once you will print ‘new_output’ then the output will display the index number which is greater than ‘120’ that is ‘1’:134.

Here is the Output of the following given code

Python find index of element in list greater than
Python find an index of the element in list greater than

Read: Python convert binary to decimal

Python find index of element in list of lists

  • In this Program, we will discuss how to find the index of elements in the list of lists in Python.
  • To perform this particular task we are going to apply the list.index() method and in this example, we will check the condition if the item is not available in the list then the index() method will raise an error.
  • In the below example we have created a list of lists and we have to find the index number of ‘321’ in the given list.

Source Code:

new_lis_lis = [["98","85","112","321","405"],["189","239","706","148","227"]]
def find(m):
    for x, new_val in enumerate(new_lis_lis):
        try:
            y = new_val.index(m)
        except ValueError:
            continue
        yield x, y

new_result = [z for z in find('321')]
print(new_result)

Here is the execution of the following given code

Python find index of element in list of lists
Python find an index of the element in a list of lists

As you can see in the Screenshot the element is present at 3 positions.

Read: Python Count Words in File

Python find index of element in list with condition

  • Let us see how to find the index of elements in the list with conditions in Python.
  • By using the list comprehension method we can easily get the index number of specific elements. In Python, list comprehension is used to iterate items through a given list and access its indexes along with values.
  • It will check the condition in len() method if no argument is passed then it will return an empty list. This method will actually help the user to reduce longer loops and make the program easier.

Example:

new_lis = [1877,18,77,30,77,45,567]

output = [ i for i in range(len(new_lis)) if new_lis[i] == 77 ]
print("Get index number from list:",output)

In the above code, we have to find the index number of ’77’ by using list comprehension. Once you will print ‘output’ then the result will display the index number of ’77’ that is 2 and 4.

You can refer to the below Screenshot

Python find index of element in list with condition
Python find an index of an element in the list with condition

Also, check: How to Find Duplicates in Python DataFrame

Python find index of item in list

  • In Python to get the index of items in a list we can apply the list comprehension of len() class with the item passed as a parameter.
  • In this example, we have to find the index of the first occurrence of values in a given list. First, we will create a list ‘new_lis’ and assign integer values to it.
  • Now use the len() method and give the condition if the value ’64’ is present in the list then it will display the index number otherwise it will return an empty list.

Source code:

new_lis = [73,123,64,52,74,86,32,64,64] 
 
output = [m for m in range(len(new_lis)) if new_lis[m] == 64] 
print("Find index of element in list:",output)

Here is the Screenshot of the following given code

Python find index of item in list
Python find an index of the item in a list

As you can see in the Screenshot the element is present at 2 7 and 8 positions.

Read: Case statement in Python

Python find index of item in list containing string

  • In this section, we will discuss how to find the index of items in the list containing string by using Python.
  • To get the index of an element in a list first, we will create a list of strings ‘new_list’ and now we want to get the index number of ‘Micheal’ which is present in the list. By default, the index value starts with 0.

Source Code:

new_list = ['George', 'Micheal', 'Micheal', 'John', 'Micheal', 'Potter'] 

emp_lis = [] 
for m in range(0, len(new_list)) : 
    if new_list[m] == 'Micheal' : 
        emp_lis.append(m)
print("Index no of 'Micheal':", emp_lis)

You can refer to the below Screenshot

Python find index of item in list containing string
Python find the index of an item in a list containing a string

Read: How to Reverse a List in Python

Python get index of element in list by value

  • In this Program, we will discuss how to get the index of elements in the list by value in Python.
  • By using the list.index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list.index() method we can get the index of the item whose value is ‘210’.

Example:

new_lis = [28, 190, 210, 567, 912, 678]

new_val = 210
result = new_lis.index(new_val)
print(result)

In the above code, we have created a list ‘new_lis’ and then initialize a variable ‘new_val’ in which we have to assign the value ‘210’. Now to find the index number of 210 we have to use the list.index() method.

Here is the implementation of the following given code

Python get index of element in list by value
Python get an index of an element in the list by value

Also, read: Get First Key in dictionary Python

Python find index of item in list without exception

  • In this Program, we will discuss how to get the index of elements in a list without using exception in Python.
  • To perform this task we can apply the Python enumerate() method and this function can be used to return the index number of all the elements which is present in the list.
  • In Python, the enumerator is basically allows us to iterate items through a sequence and this function takes in an iterable as a parameter such as lists.

Source Code:

my_new_lis = [56,92,17,39,115,189,459,512] 

new_output = [i for i, j in enumerate(my_new_lis) if j == 115] 
print("Element is present at index:",new_output)

You can refer to the below Screenshot

Python find index of item in list without exception
Python find an index of the item in a list without exception

As you can see in the Screenshot the element is present in the 4th position.

Finding an index of the item in a list without exception

  • In this example, we want to find the index of an element if it exists otherwise it will default value in Python.
  • If the value does not contain in list the it will return 2. In this example ‘420’ value is not found and a value error will be thrown.

Example:

new_element = [27,39,128,739,367,734]

try:
    new_val = new_element.index(420)
except ValueError:
    new_val = 2

print(new_val) 

Here is the Screenshot of the following given code

Python find index of item in list without exception
Python find an index of the item in a list without exception

This is how you can find the index of elements in the list without exception.

Read: Python dictionary increment value

Python find index of item in list case insensitive

  • In this section, we will discuss how to find the index of items in list case insensitive by using Python.
  • In this Program, you will convert the elements in the list to lower case by using the Python lower() method, and this function converts all uppercase characters into lowercase characters.
  • This method does not take any argument and always returns the lowercase string. In this example, we want to get the index number of the ‘S’ character. The index() method in the new_list has lower case element ‘s’.

Example:

Search_ele = 's'

my_new_lis1 =  ['M', 'Q', 'S', 'T', 'Z', 'H', 'W', 'A']
new_result = [item.lower() for item in my_new_lis1]
b = new_result.index(Search_ele.lower())
print(b)

Here is the execution of the following given code

Python find index of item in list case insensitive
Python find an index of the item in list case insensitive

As you can see in the Screenshot ‘s’ is available at the 2nd position.

Read: Python dictionary of lists

Python get index of item in list while iterating

  • Let us see how to get the index of items in the list while iterating by using Python.
  • By using the Python range() function we can easily iterate over the indices of a Python list. In Python this method will return a sequence of elements starting from 0.

Source Code:

new_lis = ['Micheal', 'John', 'Micheal']
 
for m in range(len(new_lis)):
    print((m, new_lis[m]))

Here is the implementation of the following given code

Python get index of item in list while iterating
Python get the index of an item in a list while iterating

Get the index of an item in a list while iterating

By using the enumerator() method we can solve this particular task and this method will help the user to iterate items through a sequence and this function takes in an iterable as a parameter such as lists.

Example:

list_value = [46, 81, 72, 39, 38, 1, 89,987,705,409]

for x, y in enumerate(list_value): 
    print(list((x, y))) 

You can refer to the below Screenshot

Python get index of item in list while iterating
Python get the index of an item in a list while iterating

Read: Python dictionary extend

Python get index of item in list with default

  • In this Program, we will discuss how to get the index of items in the list with default values by using Python.
  • In the given, we have set the default value as 0 for starting the index value. By using the combination of range and len() function we can easily get the index value of each element.

Source Code:

my_new_val = [78,39,117,84,47,290]

for z in range(0,len(my_new_val)):
    print([z])

Here is the Output of the following given code

Python get index of item in list with default
Python get the index of an item in a list with default

Python get index of element in list if exists

  • Here we can see how to get the index of elements in a list if exists by using Python.
  • In this example, we will use the combination of the ‘in’ operator and the index() method. In Python, the in operator will always check the condition if the value exists in the list then it will return true otherwise false. Now we are going to use the index() method and it will return the index of a particular item in the list.

Example:

Student_name = ['Olijah', 'William', 'Chris', 'James', 'Potter']
select_name = 'William'

if select_name in Student_name:
    new_output = Student_name.index(select_name)
    print("Element exist in list:",new_output)
else:
    print("Element does not exist in list:",select_name)

In the above code first, we have created a list and used an operator to check if the item ‘william’ exists in a list or not then use the index() method will get the index number of ‘william’ if it exists.

Here is the execution of the following given code

Python get index of element in list if exists
Python get an index of the element in a list if exists

As you can see in the Screenshot the element has 1st position.

Read: Python string to list

Python find index of item in list regex

  • In this section, we will discuss how to find an index of items in a list by using regular expression in Python.
  • In Python, the regex module is used to match the string based on the condition and the regex is imported through the re module.
  • In this example we use the concept of re.search() method and this function will search the regex pattern. It will check if the ‘china’ element exists in the list or not. If it exists then it will return the index number.

Source Code:

You can use the below snippet to execute this program

import re

new_lis1 = ['Germany', 'China', 'Switzerland']
new_output = [m for m, item in enumerate(new_lis1) if re.search('China', item)]
print("element index:",new_output)

Here is the Screenshot of the following given code

Python find index of item in list regex
Python find an index of the item in list regex

Read: Python Dictionary Copy

Python find a position of an item in a list

  • Let us see how to find a position of an item in a list by using Python.
  • In Python to find a position of an element in a list using the index() method and it will search an element in the given list and return its index.
  • In this example, we have to find the index number of ‘Mangoes’ to do this we are going to use the list.index() method.

Example:

fruit_name = ['Banana', 'Grapes', 'Mangoes', 'Apple']

result = fruit_name.index('Mangoes')
print("Position of element in list:",result)

You can refer to the below Screenshot

Python find a position of an item in a list
Python find a position of an item in a list

As you can see in the Screenshot the element is present in the 2nd position.

Read: Python NumPy Random

Python get index of max element in a list

  • In this program, we will discuss how to get the index of maximum element in a list.
  • In Python the max() method is used to find the maximum value in a given list and it accepts the sequence as a method parameter.
  • In this example we have also use the concept of list.index() method to find the index of a specific element from a list.

Source code:

list_elements = [89, 117, 734,864]

new_val = max(list_elements)
result = list_elements.index(new_val)
print("Maximum element index:",result)

In the above code, once you will print ‘result’ then the output will display the index number of the maximum element that is ‘864’.

Python get index of max element in a list
Python get the index of the max element in a list

As you can see in the Screenshot the maximum element is present in the 3rd position.

Read: Python dictionary multiple keys

Python find index of smallest element in list

  • Let us see how to find the index of the smallest element in a list in Python.
  • By using the Python min() method, we can easily get the minimum number that is available in the list along with we have used the index() method for finding the index of a specific element from the list.

Example:

min_list_my = [89, 64, 734,864,1167,23,45]

new_val = min(min_list_my)
result = min_list_my.index(new_val)
print("Smallest element index:",result)

You can refer to the below Screenshot

Python find index of smallest element in list
Python find an index of the smallest element in a list

As you can see in the Screenshot the minimum element is present in the 5th position.

Find index of duplicate elements in list Python

  • In this section, we will discuss how to find the index of duplicate elements in List by using Python.
  • By using the list comprehension and list slicing method we can easily get the index number of duplicate values which is present in the given list.

Source Code:

numbers_list = [83, 71, 83, 45, 83, 21, 11]

new_output = [m for m, new_val in enumerate(numbers_list) if new_val in numbers_list[:m]]
print("Duplicate element index:",new_output)

Here is the Screenshot of the following given code

Find index of duplicate elements in list Python
Find an index of duplicate elements in list Python

This is how to find the index number of duplicate values

Get the index number of duplicate values

By using the duplicated and where() method we can easily perform this particular task. In Python, duplicated() method checks the condition of whether duplicate values are available in the list or not, and the np.where() function returns the indices of duplicate values.

Source Code:

import numpy as np
import pandas as pd

my_list =  [78,489,55,78,92,78]
b=pd.DataFrame(my_list)
new_result = np.where(b.duplicated())
print("Index number of duplicate values:",new_result)

Here is the execution of the following given code

Find index of duplicate elements in list Python
Find an index of duplicate elements in list Python

Python find index of multiple elements in list

  • Here we can see how to find the index of multiple elements in a given list by using Python.
  • In this example, we have selected multiple values from a list and store them into a new list and then we apply the list comprehension method to get the index number of these values.

Source Code:

num_lis = [89,145,734,819]

result = {new_ele: m for m, new_ele in enumerate(num_lis)}
search_ele = [734,145]
b = [result.get(new_val) for new_val in search_ele]
print("Multiple index:",b)

In the above code, once you will print ‘b’ then the output will display the index number of ‘734’ and ‘145’.

You can refer to the below Screenshot

Python find index of multiple elements in list
Python find an index of multiple elements in a list

Python get index of element in list NumPy

  • In this Program, we will discuss how to get the index of elements in a list by using Python NumPy.
  • To do this task first we will create a list and then use the np.array() function to convert the list into an array. Now we want to get the index of ‘134’ number which is available in the list.

Source Code:

import numpy as np

new_numbers = [21,178,567,134,925,120,670] 
new_arr = np.array(new_numbers)
result = np.where(new_arr== 134)[0]
print(result)

Here is the execution of the following given code

Python get index of element in list NumPy
Python get an index of an element in list NumPy

As you can see in the Screenshot the element is present in the 3rd position.

Python find index of common elements in two lists

  • In this section, we will discuss how to find the index of common elements in two lists in Python.
  • First, we have created two lists and then initialize a variable ‘result’ in which we have assigned the set and the intersection method. This method will help us to get the common elements from the list. Now use the list.index() method to get the index number of those elements.

Example:

new_lis1=[87,56,36,77,58]
new_lis2=[56,44,39,12,13]

result = set(new_lis1).intersection(new_lis2)
index_lis1 = [new_lis1.index(m) for m in result]
index_lis2 = [new_lis2.index(m) for m in result]
print(index_lis1,index_lis2)

Here is the Output of the following given code

Python find index of common elements in two lists
Python find an index of common elements in two lists

Python get index of item in list comprehension

  • Let us see how to get the index of items in a list by using the Python list comprehension method. In Python, list comprehension method is used to iterate items through a given list and access its indexes along with values.
  • In this example, we will iterate over the list index and element by using the for loop method and it will check the condition if the element is ‘156’ then the value return with an index number.

Example:

int_numbers = [78, 68, 156, 289, 213, 71]

new_output = [z for z in range(len(int_numbers)) if int_numbers[z] == 156]
print(new_output)

Here is the Screenshot of the following given code

Python get index of item in list comprehension
Python get the index of an item in a list comprehension

This is how to get the index of an item in a list by using the Python list comprehension method.

You may also like the following Python tutorials:

  • Python NumPy to list with examples
  • Add string to list Python
  • Python concatenate list with examples
  • Check if a list exists in another list Python
  • Python write a list to CSV
  • Python list comprehension using if-else

In this Python tutorial, we have learned how to find the index of elements in a list by using Python. Also, we have covered these topics.

  • Python find index of element in list closest to value
  • Python find index of element in list greater than
  • Python find index of element in list of lists
  • Python find index of element in list with condition
  • Python find index of item in list
  • Python find index of object in list by attribute
  • Python find index of item in list containing string
  • Python get index of element in list by value
  • Python find index of item in list without exception
  • Python find index of item in list case insensitive
  • Python get index of item in list while iterating
  • Python get index of item in list with default
  • Python get index of element in list if exists
  • Python find index of item in list regex
  • Python find position of item in a list
  • Python get index of max element in a list.
  • Python find index of smallest element in list
  • Find index of duplicate elements in list Python
  • Python find index of multiple elements in list
  • Python get index of element in list NumPy
  • Python find index of common elements in two lists
  • Python get index of item in list comprehension

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

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