Open In App

Get index in the list of objects by attribute in Python

Last Updated : 19 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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)

Parameters:

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

Python3




# 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:
    a.append(X(i))
      
print(getIndex(a,3))


Output:

2

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.


Previous Article
Next Article

Similar Reads

Python - Get the object with the max attribute value in a list of objects
Given a list of objects, the task is to write a Python program to get the object with the max attribute value in a list of objects using Python. This task can be achieved by using the max() method and attrgetter operator. It returns a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of att
3 min read
How to get the list of all initialized objects and function definitions alive in Python?
In this article, we are going to get the list of all initialized objects and function definitions that are alive in Python, so we are getting all those initialized objects details by using gc module we can get the details. GC stands for garbage collector which is issued to manage the objects in the memory, so from that module, we are using the get_
2 min read
Python Program to get the Longest Alphabetic order of Kth index from list values
Given a string list, the task is to write a Python program to extract Strings that form the longest increasing alphabetic order at the Kth index. K should be less than the minimum length of all strings. Input : test_list = ["gfg", "is", "best", "for", "geeks", "and", "cs"], K = 0 Output : ['best', 'for', 'geeks'] Explanation : Longest subsequence e
4 min read
Get Index of Multiple List Elements in Python
In Python, retrieving the indices of specific elements in a list is a common task that programmers often encounter. There are several methods to achieve this, each with its own advantages and use cases. In this article, we will explore some different approaches to get the index of multiple list elements in Python. Get Index Of Multiple List Element
3 min read
Get a dictionary from an Objects Fields
In this article, we will discuss how to get a dictionary from object's field i.e. how to get the class members in the form of a dictionary. There are two approaches to solve the above problem: By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Python | Add list elements with a multi-list based on index
Given two lists, one is a simple list and second is a multi-list, the task is to add both lists based on index. Example: Input: List = [1, 2, 3, 4, 5, 6] List of list = [[0], [0, 1, 2], [0, 1], [0, 1], [0, 1, 2], [0]] Output: [[1], [2, 3, 4], [3, 4], [4, 5], [5, 6, 7], [6]] Explanation: [1] = [1+0] [2, 3, 4] = [0+2, 1+2, 2+2] [3, 4] = [3+0, 3+1] [4
5 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Practice Tags :