Skip to main content

How to find the index of an element in a Python list.



Hello everyone, welcome back to my blog. I thought to start a series to answer the most googled question on my blogs (this blog and https://talksofchamodh.blogspot.com) In the first episode I'm gonna show you how to find the index of an element in a list in Python. I'm sure this may have been answered before on other sites I promise you, this tutorial will be the most valuable and authentic answer for this most googled question.  





What is a List in Python

 A list is a widely used data structure in Python that allows you to store a data sequence. This data type has some unique characteristics. They allow us to manage our memory and do our stuff more efficiently.

How to find the index of an element in a list in Python?

To find the index of an element in a list, we can use an in-built method called list.index(x). It returns the first item whose value is equal to x.


For instance, I have the following list.

languages= ['python','R','C++']

And I want to find the index of 'Python'. To find the index I call the method shown below.


print(languages.index('python'))


And it returns the zero-based index '0'


What if, I add another 'python' to the list and repeat. I will also return '0' because it only returns the index of the first item.

Give it a try.


languages= ['python','R','C++','python']

And also, the index method has another optional argument called start and end. It allows us to scan for an item in a particular subsequence in our list using the slice notation.


For example, if we want to get the second 'python' index, we have to limit our search to a subsequence that doesn't have the first Python.


 print(languages.index('python',1,4))

This returns 3 as the index of 'python' as the search is asked to omit the first python.


The format of the index method is as follows.

list.index(value,start_index,end_index+1)


If there is no item whose value is equal to the given value, the method returns a ValueError as follows.

languages= ['python','R','C++','python']

print(languages.index('HTML',0,4))

Traceback (most recent call last): File "f:\New folder\list index finder.py", line 3, in <module> print(languages.index('HTML',0,4)) ValueError: 'HTML' is not in list







Method 2


Instead of the built-in index method, we can create our own method to find the index.

This is how I coded that but there may be other ways to do it.

Don't forget to share your comment below in the comment section and share this with your friends.



languages= ['python','R','C++','python']

def index(seq,val):
    for count,value in enumerate(languages):
        if value == val:
            return count
            break
        else:
            pass

print(index(languages,'python'))




Here I compare all the values with the value given and if an item matches, it will return the index of that item and break the loop so that only the index of the first item is returned.


That's all and hope you learned something interesting.

Thank you for reading and don't forget to share this on your social media platforms.

Comments

Trending Now

Let's talk about cryptography.

Have you ever heard of cryptography?  People write their diaries every day. For many of them, their diary is one of their best friends to whom they tell their every secret. What happens when someone else finds such a diary? That would freak out the dairy's owner for sure. Also, it might put their lives in danger. Wise men always hide their diaries so no one else finds it.  But legends hide their message so that only they can read what they wrote. So even if the diary is found by someone else, they cannot know the secrets. for example, I wrote this in my diary today.   P dyval h isvn wvza hivba jyfwavnyhwof avkhf Can you understand it? This is just a very primitive level of cryptography yet powerful enough to hide what I wrote from 90% of people. I will discuss this type of cryptography in the next blog post. The human used cryptography from the very beginning to share their messages in secret and conceal their inventions. As you may know, many people tried to find a recip...

Generate all possible phone numbers with Python | Generates Crores of Phone Numbers within minutes.

Recently,  I learned about itertools in python. Especially, about the functions permutations, combinations, and products and I tried to make a script that generates all phone numbers in our country. I bet your phone number is too on the list. let the hack begin!!! First, you need to install itertools in your computer  Simply open your terminal and type                sudo apt-get  install  -y python-more- itertools Then Write the code below from itertools import product file_name = "phonebook.txt" phonebook = open (file_name, 'a' ) prefixes = [ '+9471' ] product_a = product([ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' ], [ '1' , '2' , '3' , '4' , '5...