Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get index in the list of objects by attribute in Python
Lists are a common data structure in Python for storing a collection of objects. Sometimes you need to find the index of a specific item in the list based on an attribute value. Python provides several efficient methods for getting the index in a list of objects by attribute.
Syntax
To find the index in a list of objects by attribute, use this syntax ?
index = next((i for i, obj in enumerate(my_list) if obj.attribute == desired_value), None)
The next() method returns the first index where the object's attribute matches the desired value. If no matching object is found, it returns None.
Using next() with Generator Expression
This is the most memory-efficient approach for finding an object's index by attribute ?
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
employees = [
Employee("John", 30, 50000),
Employee("Alice", 25, 45000),
Employee("Bob", 35, 55000)
]
# Find index of employee named "Alice"
index = next((i for i, obj in enumerate(employees) if obj.name == "Alice"), None)
print(f"Alice is at index: {index}")
# Find index of employee with salary 55000
salary_index = next((i for i, obj in enumerate(employees) if obj.salary == 55000), None)
print(f"Employee with salary 55000 is at index: {salary_index}")
Alice is at index: 1 Employee with salary 55000 is at index: 2
Using List Comprehension with index()
Create a list of matching attributes and find the first occurrence ?
class Product:
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
products = [
Product(1, "Laptop", 999),
Product(2, "Mouse", 25),
Product(3, "Keyboard", 75)
]
# Find index of product with ID 2
names = [p.name for p in products]
try:
index = names.index("Mouse")
print(f"Mouse is at index: {index}")
except ValueError:
print("Product not found")
Mouse is at index: 1
Using a Custom Function
Create a reusable function for finding indices by any attribute ?
def find_index_by_attribute(obj_list, attr_name, attr_value):
"""Find index of object by attribute value"""
for i, obj in enumerate(obj_list):
if getattr(obj, attr_name) == attr_value:
return i
return None
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
students = [
Student("Emma", "A"),
Student("Liam", "B"),
Student("Olivia", "A+")
]
# Find student by name
index = find_index_by_attribute(students, "name", "Liam")
print(f"Liam is at index: {index}")
# Find student by grade
grade_index = find_index_by_attribute(students, "grade", "A+")
print(f"Student with A+ grade is at index: {grade_index}")
Liam is at index: 1 Student with A+ grade is at index: 2
Comparison of Methods
| Method | Memory Usage | Performance | Best For |
|---|---|---|---|
next() + generator |
Low | Fast (stops early) | Single searches |
| List comprehension | High | Slower (creates list) | Multiple searches |
| Custom function | Low | Fast | Reusable code |
Handling Multiple Matches
Find all indices where the attribute matches the desired value ?
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
books = [
Book("1984", "Orwell", 1949),
Book("Animal Farm", "Orwell", 1945),
Book("Brave New World", "Huxley", 1932),
Book("Homage to Catalonia", "Orwell", 1938)
]
# Find all books by Orwell
orwell_indices = [i for i, book in enumerate(books) if book.author == "Orwell"]
print(f"Orwell books at indices: {orwell_indices}")
Orwell books at indices: [0, 1, 3]
Conclusion
Use next() with a generator expression for memory-efficient single searches. For multiple searches or when you need all matching indices, use list comprehension. The custom function approach provides the most flexibility for reusable code.
