Open In App
Related Articles

Get index in the list of objects by attribute in Python

Improve Article
Save Article
Like Article

In this article, we’ll look at how to find the index of an item in a list using an attribute in Python. We’ll use the enumerate function to do this. 

The enumerate() function produces a counter that counts how many times a loop has been iterated. We don’t need to import additional libraries to utilize the enumerate() function because it’s built-in to Python. If we use enumerate function() then we don’t have to worry about making a range() statement and then retrieving the length of an array. The enumerate function maintains two values: the item’s index and its value. 

Syntax: enumerate(iterable, start=0)


  • iterable: any object that supports iteration
  • start: the index value from which the counter is
  • to be started, by default it is 0


# This code gets the index in the
# list of objects by attribute.
class X:
    def __init__(self,val):
        self.val = val
def getIndex(li,target):
    for index, x in enumerate(li):
        if x.val == target:
            return index
    return -1
# Driver code
li = [1,2,3,4,5,6]
# Converting all the items in
# list to object of class X
a = list()
for i in li:



In this code, we are first constructing a class X, for instance, with the attribute val. Now we’ll write a function for our task (here we’ve called it getIndex()) that will return the index of the item we’re looking for using attribute, or -1 if the item doesn’t exist in our list. We’ll utilize the enumerate method in getIndex(), and as you can see, we’ve used two variables in our for loop (index and x) because the enumerate function keeps track of the item’s index and value, and we need to store both values to complete our task. We have an if condition inside our for loop that says if the val attribute of item x from the list has the same value as the target value, then return its index value. The enumerate function provides these index values. Now let’s look at how it works. we’ve defined a list, for example, within variable li, and we are going to convert this list of integer values into a list of objects. Now we’ve passed this list to the getIndex function, along with the target value for which I’m looking for an index.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Dec, 2021
Like Article
Save Article
Similar Reads
Related Tutorials