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
Post a Comment