Find the index of an element in a list python

Find the index of an element in a list python

You can find the index of an element in a list in different ways.

In this tutorial, we will do this by using:

  • index() method
  • for loop
  • Enumerate function
  • the in operator

So let’s dive into it.

What is a list index in Python?

In Python, an index of a list is a numeric value that represents the position of an element within the list.

The index of the first element in a list is always 0, the index of the second element is 1, and so on.

You can access a specific element in a list using its index by enclosing the index within square brackets after the name of the list.

For example, if you have a list called “fruits” with the following elements:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']

In this list of fruits,

the index of the apple is 0.

And the index of the banana is 1.

The index of orange is 2.

Next, the index of the kiwi is 3.

Lastly, the index of mango is 4.

You can access the element ‘banana’ using its index (which is 1) as follows:

print(fruits[1])

Output

banana

Indexing is an important concept in Python programming.

Now, let’s find out how you can find the index of a specific element in the list.

Using index() method

In Python, you can find the index of an element in a list using the index() method.

Here is the syntax of the index() method in Python.

Syntax

index(element, start, end)

The start and end are the optional arguments.

These represent the index numbers.

We will discuss it later in the article.

The index() method returns the index of the first occurrence of the specified element in the list.

Here’s an example:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']
index = fruits.index('kiwi')
print(index)

Output

3

In this example, we have a list called fruits containing several string elements.

We use the index() method to find the index of the string ‘kiwi’.

We store the result in the variable index.

Finally, we print the value of the index.

Which is the index of ‘kiwi’ in the list.

Note that if the element is not present in the list, the index() method will raise a ValueError.

In such cases, you may want to handle the exception using a try-except block.

fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']
try:
    index = fruits.index('burger')
    print(index)
except:
    print("Index not found")

Output

Index not found

There is a problem with the index() method.

It returns only the index of the first occurrence of the element.

fruits = ['apple', 'banana', 'orange', 'kiwi', 'banana', 'mango', 'banana']
try:
    index = fruits.index('banana')
    print(index)
except:
    print("Index not found")

Output

1

You can see, we just received the index of the first occurrence of the banana.

Which is index 1.

But if you want to get the indices of all the banana in the list?

While using the index(), there is one solution for this.

Do you remember the optional arguments to the index() method?

Yes, start and end.

We can use these to find the index of duplicate list items.

fruits = ['apple', 'banana', 'orange', 'kiwi', 'banana', 'mango', 'banana']
element = 'banana'
start = 2
end = len(fruits)
try:
    index = fruits.index(element, start, end)
    print(index)
except:
    print("Index not found")

Output

4

We declared two variables start and end.

start represents the starting index to search the element.

And end represents the ending element.

But still, we have got 1 index only.

We can loop through the list and update the start variable every time we find the item.

Here is how it will work:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'banana', 'mango', 'banana']
fruit_indices = []
element = 'banana'
start = 0
end = len(fruits)

while start<=end:
    try:
        index = fruits.index(element, start, end)
        fruit_indices.append(index)
        start = index + 1
    except:
        break
    
print(fruit_indices)

Output

[1, 4, 6]

We created two variables start and end.

We initiated the start as 0.

And, the end was determined from the length of the list by using the len() method.

We then started a loop, the while loop ran until the start was less than the end.

In the loop, we add the index to list fruit indices.

At the same time, we incremented the start to index+1.

Finally, we print the fruit_indices.

Let’s make it a little easy and do it with a for loop.

Using a for loop

You can use a for loop to do so.

You have to create a new empty list.

Where you can store the indices of banana.

fruits = ['apple', 'banana', 'orange', 'kiwi', 'banana', 'mango', 'banana']
element = 'banana'
banana_indices = []
try:
    for index in range(len(fruits)):
        if fruits[index] == element:
            banana_indices.append(index)
    print(banana_indices)
except:
    print("Index not found")

Output

[1, 4, 6]

Now, you have all the indices in a list.

Using enumerate() function

In Python, the enumerate() function is a built-in function.

This function allows you to iterate over a sequence (e.g. a list, tuple, or string).

You can keep track of the index of each element along with the corresponding element.

The function takes a sequence as its argument.

And returns an iterator that produces pairs consisting of the index and the corresponding element.

Here’s an example of how to use the enumerate() function:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']
for index, item in enumerate(fruits):
    print(index, item)

Output

0 apple
1 banana
2 orange
3 kiwi
4 mango

In this example, we use the enumerate() function to iterate over this list.

In (index, item), index represents the index of each element of the list.

Whereas, the item represents a list item that corresponds to that index.

We can keep track of the index and item at the same time using enumerate function.

Inside the loop, we print the index and the corresponding element using the print() function.

Using the enumerate function, you can find the index of an element in a list as well.

my_list = ['apple', 'banana', 'orange', 'kiwi', 'mango']
element = 'kiwi'
for i, value in enumerate(my_list):
    if value == element:
        index = i
        break
print(index)

Output

3

Using the in operator with index() method

You can also find the index of an element in a list using the in operator with the index() method.

Here’s an example:

fruits = ['apple', 'banana', 'orange', 'kiwi', 'mango']
element = input('Enter the fruit to find its index: ')
if element in fruits:
    index = fruits.index(element)
    print(element, 'found at index',index)
else:
    print(element, 'not found in the list')

The in operator will search for the element in the fruit list.

If the in operator found the element, it will execute the code in the if block.

Otherwise, the code from the else block will be executed.

Output

Enter the fruit to find its index: kiwi
kiwi found at index 3

Kiwi was found at index 3 as it was present in the list.

But if the element is not in the list, the program will run the else statement.

Enter the fruit to find its index: burger
burger not found in the list

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x