Saturday, October 24, 2020

Python — Finding the index of an item in a list



If you are working as Python developer, data analysts or data scientists for any organisation then it is very important for you to know how to play with Lists and get the requested info such as matching indexes or items from them.

If you want to get all the occurrences and the position of one or more items in a list by using Python then there are many ways but you need a very sufficient way to get the matching items from the list.

Let’s see the below example —

Now, you can see here, we have created a list of fruits and want to get the occurrence of Apple from the list and Python program will store this list as given below -
Image for post
Note — Python is a zero indexed based language

In the above list, you can see that Python based list is starting with 0 index and end with total item-1. In our cases, last index value in our fruit list will be 6–1 =5

Now, this point is How to get the occurrence of a item in the list. You could use a list comprehension with enumerate too such as given below -

Better data munging with pandas — If you have pandas, you can easily get this information with a Series object:

Now, we have converted list into series by using pandas library or package and we will be able to get a comparison check which will return a series of Booleans:

If you try to pass that series of Booleans to the series via subscript notation, and you get just the matching members:

In this case, if you want them in a list or tuple, just pass them to the constructor as given below:

Through For Loop — This is the another options to get the matching items from a given list, only for those coming from another language and may be with a simple loop it’s easier to understand and use it:

If you’re munging data, you should most probably be using pandas because it has far more elegant tools than the pure Python workarounds. Another fact is that, there are many ways to list down the matching indexes from the list but you must have to careful with your code efficiency.
To learn more, please follow us -
To Learn more, please visit our YouTube channel at - 
To Learn more, please visit our Instagram account at -
To Learn more, please visit our twitter account at -
To Learn more, please visit our Medium account at -

No comments:

Post a Comment

Popular Posts