Изучая программирование на 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».
Finding the index of an item given a list containing it in Python
For a list
["foo", "bar", "baz"]
and an item in the list"bar"
, what’s the cleanest way to get its index (1) in Python?
Well, sure, there’s the index method, which returns the index of the first occurrence:
>>> l = ["foo", "bar", "baz"]
>>> l.index('bar')
1
There are a couple of issues with this method:
- if the value isn’t in the list, you’ll get a
ValueError
- if more than one of the value is in the list, you only get the index for the first one
No values
If the value could be missing, you need to catch the ValueError
.
You can do so with a reusable definition like this:
def index(a_list, value):
try:
return a_list.index(value)
except ValueError:
return None
And use it like this:
>>> print(index(l, 'quux'))
None
>>> print(index(l, 'bar'))
1
And the downside of this is that you will probably have a check for if the returned value is
or is not
None:
result = index(a_list, value)
if result is not None:
do_something(result)
More than one value in the list
If you could have more occurrences, you’ll not get complete information with list.index
:
>>> l.append('bar')
>>> l
['foo', 'bar', 'baz', 'bar']
>>> l.index('bar') # nothing at index 3?
1
You might enumerate into a list comprehension the indexes:
>>> [index for index, v in enumerate(l) if v == 'bar']
[1, 3]
>>> [index for index, v in enumerate(l) if v == 'boink']
[]
If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:
indexes = [index for index, v in enumerate(l) if v == 'boink']
for index in indexes:
do_something(index)
Better data munging with pandas
If you have pandas, you can easily get this information with a Series object:
>>> import pandas as pd
>>> series = pd.Series(l)
>>> series
0 foo
1 bar
2 baz
3 bar
dtype: object
A comparison check will return a series of booleans:
>>> series == 'bar'
0 False
1 True
2 False
3 True
dtype: bool
Pass that series of booleans to the series via subscript notation, and you get just the matching members:
>>> series[series == 'bar']
1 bar
3 bar
dtype: object
If you want just the indexes, the index attribute returns a series of integers:
>>> series[series == 'bar'].index
Int64Index([1, 3], dtype='int64')
And if you want them in a list or tuple, just pass them to the constructor:
>>> list(series[series == 'bar'].index)
[1, 3]
Yes, you could use a list comprehension with enumerate too, but that’s just not as elegant, in my opinion – you’re doing tests for equality in Python, instead of letting builtin code written in C handle it:
>>> [i for i, value in enumerate(l) if value == 'bar']
[1, 3]
Is this an XY problem?
The XY problem is asking about your attempted solution rather than your actual problem.
Why do you think you need the index given an element in a list?
If you already know the value, why do you care where it is in a list?
If the value isn’t there, catching the ValueError
is rather verbose – and I prefer to avoid that.
I’m usually iterating over the list anyways, so I’ll usually keep a pointer to any interesting information, getting the index with enumerate.
If you’re munging data, you should probably be using pandas – which has far more elegant tools than the pure Python workarounds I’ve shown.
I do not recall needing list.index
, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.
There are many, many uses for it in idlelib
, for GUI and text parsing.
The keyword
module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.
In Lib/mailbox.py it seems to be using it like an ordered mapping:
key_list[key_list.index(old)] = new
and
del key_list[key_list.index(key)]
In Lib/http/cookiejar.py, seems to be used to get the next month:
mon = MONTHS_LOWER.index(mon.lower())+1
In Lib/tarfile.py similar to distutils to get a slice up to an item:
members = members[:members.index(tarinfo)]
In Lib/pickletools.py:
numtopop = before.index(markobject)
What these usages seem to have in common is that they seem to operate on lists of constrained sizes (important because of O(n) lookup time for list.index
), and they’re mostly used in parsing (and UI in the case of Idle).
While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you’re doing is the most direct usage of the tools provided by the language for your use-case.
In this article you will learn how to find the index of an element contained in a list in the Python programming language.
There are a few ways to achieve this, and in this article you will learn three of the different techniques used to find the index of a list element in Python.
The three techniques used are:
- finding the index using the
index()
list method, - using a
for-loop
, - and finally, using list comprehension and the
enumerate()
function.
Specifically, here is what we will cover in depth:
- An overview of lists in Python
- How indexing works
- Use the
index()
method to find the index of an item
1.Use optional parameters with theindex()
method - Get the indices of all occurrences of an item in a list
- Use a
for-loop
to get indices of all occurrences of an item in a list - Use list comprehension and the
enumerate()
function to get indices of all occurrences of an item in a list
- Use a
What are Lists in Python?
Lists are a built-in data type in Python, and one of the most powerful data structures.
They act as containers and store multiple, typically related, items under the same variable name.
Items are placed and enclosed inside square brackets, []
. Each item inside the square brackets is separated by a comma, ,
.
# a list called 'my_information' that contains strings and numbers
my_information = ["John Doe", 34, "London", 1.76]
From the example above, you can see that lists can contain items that are of any data type, meaning list elements can be heterogeneous.
Unlike arrays that only store items that are of the same type, lists allow for more flexibility.
Lists are also mutable, which means they are changeable and dynamic. List items can be updated, new items can be added to the list, and any item can be removed at any time throughout the life of the program.
An Overview of Indexing in Python
As mentioned, lists are a collection of items. Specifically, they are an ordered collection of items and they preserve that set and defined order for the most part.
Each element inside a list will have a unique position that identifies it.
That position is called the element’s index.
Indices in Python, and in all programming languages, start at 0
and not 1
.
Let’s take a look at the list that was used in the previous section:
my_information = ["John Doe", 34, "London", 1.76]
The list is zero-indexed and counting starts at 0
.
The first list element, "John Doe"
, has an index of 0
.
The second list element, 34
, has an index of 1
.
The third list element, "London"
, has an index of 2
.
The forth list element, 1.76
, has an index of 3
.
Indices come in useful for accessing specific list items whose position (index) you know.
So, you can grab any list element you want by using its index.
To access an item, first include the name of the list and then in square brackets include the integer that corresponds to the index for the item you want to access.
Here is how you would access each item using its index:
my_information = ["John Doe", 34, "London", 1.76]
print(my_information[0])
print(my_information[1])
print(my_information[2])
print(my_information[3])
#output
#John Doe
#34
#London
#1.76
But what about finding the index of a list item in Python?
In the sections that follow you will see some of the ways you can find the index of list elements.
So far you’ve seen how to access a value by referencing its index number.
What happens though when you don’t know the index number and you’re working with a large list?
You can give a value and find its index and in that way check the position it has within the list.
For that, Python’s built-in index()
method is used as a search tool.
The syntax of the index()
method looks like this:
my_list.index(item, start, end)
Let’s break it down:
my_list
is the name of the list you are searching through..index()
is the search method which takes three parameters. One parameter is required and the other two are optional.item
is the required parameter. It’s the element whose index you are searching for.start
is the first optional parameter. It’s the index where you will start your search from.end
the second optional parameter. It’s the index where you will end your search.
Let’s see an example using only the required parameter:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("Python"))
#output
#1
In the example above, the index()
method only takes one argument which is the element whose index you are looking for.
Keep in mind that the argument you pass is case-sensitive. This means that if you had passed “python”, and not “Python”, you would have received an error as “python” with a lowercase “p” is not part of the list.
The return value is an integer, which is the index number of the list item that was passed as an argument to the method.
Let’s look at another example:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("React"))
#output
#line 3, in <module>
# print(programming_languages.index("React"))
#ValueError: 'React' is not in list
If you try and search for an item but there is no match in the list you’re searching through, Python will throw an error as the return value – specifically it will return a ValueError
.
This means that the item you’re searching for doesn’t exist in the list.
A way to prevent this from happening, is to wrap the call to the index()
method in a try/except
block.
If the value does not exist, there will be a message to the console saying it is not stored in the list and therefore doesn’t exist.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
try:
print(programming_languages.index("React"))
except ValueError:
print("That item does not exist")
#output
#That item does not exist
Another way would be to check to see if the item is inside the list in the first place, before looking for its index number. The output will be a Boolean value – it will be either True or False.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print("React" in programming_languages)
#output
#False
How to Use the Optional Parameters with the index()
Method
Let’s take a look at the following example:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python"))
#output
#1
In the list programming_languages
there are three instances of the “Python” string that is being searched.
As a way to test, you could work backwards as in this case the list is small.
You could count and figure out their index numbers and then reference them like you’ve seen in previous sections:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages[1])
print(programming_languages[3])
print(programming_languages[5])
#output
#Python
#Python
#Python
There is one at position 1
, another one at position 3
and the last one is at position 5
.
Why aren’t they showing in the output when the index()
method is used?
When the index()
method is used, the return value is only the first occurence of the item in the list. The rest of the occurrences are not returned.
The index()
method returns only the index of the position where the item appears the first time.
You could try passing the optional start
and end
parameters to the index()
method.
You already know that the first occurence starts at index 1
, so that could be the value of the start
parameter.
For the end
parameter you could first find the length of the list.
To find the length, use the len()
function:
print(len(programming_languages))
#output is 6
The value for end
parameter would then be the length of the list minus 1. The index of the last item in a list is always one less than the length of the list.
So, putting all that together, here is how you could try to get all three instances of the item:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python",1,5))
#output
#1
The output still returns only the first instance!
Although the start
and end
parameters provide a range of positions for your search, the return value when using the index()
method is still only the first occurence of the item in the list.
How to Get the Indices of All Occurrences of an Item in A List
Use a for-loop
to Get the Indices of All Occurrences of an Item in A List
Let’s take the same example that we’ve used so far.
That list has three occurrences of the string “Python”.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
First, create a new, empty list.
This will be the list where all indices of “Python” will be stored.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
Next, use a for-loop
. This is a way to iterate (or loop) through the list, and get each item in the original list. Specifically, we loop over each item’s index number.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
You first use the for
keyword.
Then create a variable, in this case programming_language
, which will act as a placeholder for the position of each item in the original list, during the iterating process.
Next, you need to specify the set amount of iterations the for-loop
should perform.
In this case, the loop will iterate through the full length of the list, from start to finish. The syntax range(len(programming_languages))
is a way to access all items in the list programming_languages
.
The range()
function takes a sequence of numbers that specify the number it should start counting from and the number it should end the counting with.
The len()
function calculates the length of the list, so in this case counting would start at 0
and end at – but not include – 6
, which is the end of the list.
Lastly, you need to set a logical condition.
Essentially, you want to say: “If during the iteration, the value at the given position is equal to ‘Python’, add that position to the new list I created earlier”.
You use the append()
method for adding an element to a list.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
if programming_languages[programming_language] == "Python":
python_indices.append(programming_language)
print(python_indices)
#output
#[1, 3, 5]
Use List Comprehension and the enumerate()
Function to Get the Indices of All Occurrences of an Item in A List
Another way to find the indices of all the occurrences of a particular item is to use list comprehension.
List comprehension is a way to create a new list based on an existing list.
Here is how you would get all indices of each occurrence of the string “Python”, using list comprehension:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = [index for (index, item) in enumerate(programming_languages) if item == "Python"]
print(python_indices)
#[1, 3, 5]
With the enumerate()
function you can store the indices of the items that meet the condition you set.
It first provides a pair (index, item
) for each element in the list (programming_languages
) that is passed as the argument to the function.
index
is for the index number of the list item and item
is for the list item itself.
Then, it acts as a counter which starts counting from 0
and increments each time the condition you set is met, selecting and moving the indices of the items that meet your criteria.
Paired with the list comprehension, a new list is created with all indices of the string “Python”.
Conclusion
And there you have it! You now know some of the ways to find the index of an item, and ways to find the indices of multiple occurrences of an item, in a list in Python.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Thanks for reading and happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Python index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the index of the first occurrence.
How to find the index of an element or items in a list
In this article, we will cover different examples to find the index, such as:
- Find the index of the element
- Working of the index() With Start and End Parameters
- Working of the index() With two Parameters only
- Index of the Element not Present in the List
- How to fix list index out of range
Syntax of index() Method
Syntax: list_name.index(element, start, end)
Parameters:
- element – The element whose lowest index will be returned.
- start (Optional) – The position from where the search begins.
- end (Optional) – The position from where the search ends.
Return: Returns the lowest index where the element appears.
Error: If any element which is not present is searched, it raises a ValueError.
Example 1: Find the index of the element
Finding index of ‘bat’ using index() on Python List list2
Python3
list2
=
[
'cat'
,
'bat'
,
'mat'
,
'cat'
,
'pet'
]
print
(list2.index(
'bat'
))
Output:
1
Example 2: Working of the index() With Start and End Parameters
In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position.
Python3
list1
=
[
1
,
2
,
3
,
4
,
1
,
1
,
1
,
4
,
5
]
print
(list1.index(
4
,
4
,
8
))
Output:
7
Example 3: Working of the index() With two Parameters only
In this example, we will see when we pass two arguments in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins.
list_name.index(element, start)
Python3
list1
=
[
6
,
8
,
5
,
6
,
1
,
2
]
print
(list1.index(
6
,
1
))
Output:
3
Example 4: Index of the Element not Present in the List
Python List index() raises ValueError, when the search element is not present inside the List.
Python3
list1
=
[
1
,
2
,
3
,
4
,
1
,
1
,
1
,
4
,
5
]
print
(list1.index(
10
))
Output:
Traceback (most recent call last): File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in print(list1.index(10)) ValueError: 10 is not in list
Example 5: How to fix list index out of range using Index()
Here we are going to create a list and then try to iterate the list using the constant values in for loops.
Python3
li
=
[
1
,
2
,
3
,
4
,
5
]
for
i
in
range
(
6
):
print
(li[i])
Output:
1 2 3 4 5 IndexError: list index out of range
Reason for the error: The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.
Solving this error without using len() or constant Value:
To solve this error we will take the index of the last value of the list and then add one, then it will become the exact value of length.
Python3
li
=
[
1
,
2
,
3
,
4
,
5
]
for
i
in
range
(li.index(li[
-
1
])
+
1
):
print
(li[i])
Last Updated :
17 Aug, 2022
Like Article
Save Article
To find the index of a list element in Python, use the built-in index() method.
For example, let’s find the first string that equals “Bob” in a list of strings:
names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1
To find the index of a character in a string, use the index() method on the string.
For example, let’s find the first occurrence of the letter w in a string:
"Hello world".index("w") # returns 6
This is the quick answer.
In this guide, we are going to take a deeper dive into finding the index of an element in Python.
You are going to learn:
- How the index() method works.
- How to get multiple indexes of all similar elements.
- How to find the index of a list element.
- How to find the index of a character in a string.
In Python, a list has a built-in index() method.
This method returns the index of the first element that matches with the parameter.
The syntax for the index() function is as follows:
list.index(obj)
Where:
- list is the list we are searching for.
- obj is the object we are matching with.
Let’s see some examples of using the index() method in Python.
How to Find the Index of a List Element in Python
You can use the index() method to find the index of the first element that matches with a given search object.
For instance, let’s find the index of “Bob” in a list of names:
names = ["Alice", "Bob", "Charlie"] names.index("Bob") # Returns 1
The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.
But this method has a little problem you need to understand.
If the element you are searching for does not exist, this method throws an error that crashes the program if not handled correctly.
For example, let’s search for “David” in the list of names:
names = ["Alice", "Bob", "Charlie"] idx = names.index("David")
Output:
ValueError: 'David' is not in list
You certainly don’t want your program to crash when searching for a non-existent value.
To fix this issue, you should check that the element is in the sequence, to begin with. To do this, use the in statement with a simple if-else statement.
For example:
names = ["Alice", "Bob", "Charlie"] if "David" in names: idx = names.index("David") else: print("Not found.")
Output:
Not found.
Now the above code no longer throws an error. The index search does not even start if the item is not there.
Now you know how to use the index() method to find an index of an object in a list.
Next, let’s take a look at how you can use a similar approach to finding the index of a character in a string.
How to Find the Index of a String Character in Python
To find an index of a character in a string, follow the same procedure as finding an index in a list.
- Check if the character is in the string using the in statement.
- Find the index of the character using the index() method of a string.
For example:
sentence = "Hello world" if "x" in sentence: idx = sentence.index("x") else: print("Not found.")
Output:
Not found.
With strings, you can also search for longer substrings or words.
For example, let’s find the index of a substring “wor” in “Hello world”:
sentence = "Hello world" substr = "wor" if substr in sentence: idx = sentence.index(substr) print(idx) else: print("Not found.")
Output:
6
This returns the starting position of the substring “wor”.
Now you understand how to use the index() method in Python.
However, this method only returns the first index. Let’s take a look at how you can get all the indexes instead.
How to Get All Indexes of a List in Python
In the previous examples, you have seen how to get the first index of an element that is equal to the object we are searching for.
However, sometimes you might want to find the indexes of all the elements that equal something.
To get all the indexes:
- Couple the elements of a list with an index using the enumerate() function.
- Loop over the enumerated elements.
- Check if the index, item pair’s item matches with the object you are searching for.
- Add the index into a result list.
Here is a generator function that does exactly that:
def indexes(iterable, obj): result = [] for index, elem in enumerate(iterable): if elem == obj: yield index
Or if you want to use a shorthand, you can also use a generator comprehension:
def indexes(iterable, obj): return (index for index, elem in enumerate(iterable) if elem == obj)
Anyway, let’s use this function:
names = ["Alice", "Alice", "Bob", "Alice", "Charlie", "Alice"] idxs = indexes(names, "Alice") print(list(idxs))
Output:
[0, 1, 3, 5]
As you can see, now this function finds all the indexes of “Alice” in the list.
You can also call it for other iterables, such as a string:
sentence = "Hello world" idxs = indexes(sentence, "l") print(list(idxs))
Output:
[2, 3, 9]
Conclusion
Today you learned how to get the index of an element in a list in Python. You also saw how to get all the indexes that match with an object.
To recap, use the index() method to find the index of an element in Python. You can use it the same way for lists and strings. It finds the first occurrence of a specified element in the sequence.
To get all the indexes:
- Implement a function that couples each element with an index.
- Loop through the coupled elements.
- Pick the indexes of the elements that match with the search object.
Thanks for reading. I hope you find it useful.
Happy coding!
Further Reading
50 Python Interview Questions and Answers
50+ Buzzwords of Web Development
About the Author
-
I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts