Search
What is Indexing in Python?
In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number. Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on. For example, if we have a string "Hello", we can access the first letter "H" using its index 0 by using the square bracket notation: string[0]
.
Python's built-in index()
function is a useful tool for finding the index of a specific element in a sequence. This function takes an argument representing the value to search for and returns the index of the first occurrence of that value in the sequence.
If the value is not found in the sequence, the function raises a ValueError. For example, if we have a list [1, 2, 3, 4, 5]
, we can find the index of the value 3
by calling list.index(3)
, which will return the value 2
(since 3
is the third element in the list, and indexing starts at 0).
The index()
function is a powerful tool in Python as it simplifies the process of finding the index of an element in a sequence, eliminating the need for writing loops or conditional statements. This function is especially useful when working with large datasets or complex structures, where manual searching could be time-consuming and error-prone.
Python Index Examples
The method index()
returns the lowest index in the list where the element searched for appears. If any element which is not present is searched, it returns a ValueError.
Lets try this:
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] element = 3 list_numbers.index(element)
OpenAI
2
OpenAI
list_numbers = [4, 5, 6, 7, 8, 9, 10] element = 3 # Not in the list list_numbers.index(element) # Throws a ValueError
OpenAI
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-35-6a006c988b06> in <module>() 1 list_numbers = [4, 5, 6, 7, 8, 9, 10] 2 element = 3 # Not in the list ----> 3 list_numbers.index(element) # Throws a ValueError ValueError: 3 is not in list
OpenAI
Index of a string element
Let's try it with string elements:
list_numbers = [1, 'two', 3, 4, 5, 6, 7, 8, 9, 10] element = 'two' list_numbers.index(element)
OpenAI
1
OpenAI
What does it mean to return the lowest index?
Imagine you have more than one instance of an element, then index()
will give you the first position where the element appears.
list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10] element = 3 list_numbers.index(element)
OpenAI
0
OpenAI
The position returned is 0, because 3
first appears in the first position or the 0th index in Python.
Here is what's happening internally: index is going through all values starting from the 1st position (0th index) looking for the element you are searching for, and as soon as it finds the value - it returns the position and exits the system. However, this is not too efficient when going through a large list and you need to get the position of something towards the end of the list.
index()
provides you an option to give it hints to where the value searched for might lie
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] element = 7 list_numbers.index(element, 5, 8)
OpenAI
6
OpenAI
So the syntax is: list_name.index(element, start, stop).
Here the start
and stop
values are optional. In fact, only use it when entirely sure about the range else you will get a ValueError as below.
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] element = 7 list_numbers.index(element, 1, 5)
OpenAI
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-39-b96f4b5e51d5> in <module>() 1 list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 2 element = 7 ----> 3 list_numbers.index(element, 1, 5) ValueError: 7 is not in list
OpenAI
List Comprehension or Generator Expression
Since the index()
only returns the first match to an object, you can use list comprehension, or generator expression if you need the positions of more matches in the list. Here is how:
list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10] [i for i, n in enumerate(list_numbers) if n == 3] # List comprehension
OpenAI
[0, 3, 4, 8]
OpenAI
list_numbers = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
g = (i for i, n in enumerate(list_numbers) if n == 3) # Generator expression
print("Generators store values, the first value here is:", next(g), ". Then the next is:", next(g), "followed by ", next(g),"and finally ", next(g))
Generators store values, the first value here is: 0. Then the next is: 3 followed by 4 and finally 8