Get index in the list of objects by attribute in Python
Here's an alternative that doesn't use an (explicit) loop, with two different approaches to generating the list of 'id' values from the original list.
try:
# index = map(operator.attrgetter('id'), my_list).index('specific_id')
index = [ x.id for x in my_list ].index('specific_id')
except ValueError:
index = -1
Use enumerate
when you want both the values and indices in a for
loop:
for index, item in enumerate(my_list):
if item.id == 'specific_id':
break
else:
index = -1
Or, as a generator expression:
index = next((i for i, item in enumerate(my_list) if item.id == 'specific_id'), -1)