Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index in the list of objects by attribute in Python

Tags:

I have list of objects with attribute id and I want to find index of object with specific id. I wrote something like this:

index = -1 for i in range(len(my_list)):     if my_list[i].id == 'specific_id'         index = i         break 

but it doesn't look very well. Are there any better options?

like image 882
sebaszw Avatar asked Oct 03 '13 14:10

sebaszw


1 Answers

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) 
like image 188
Joel Cornett Avatar answered Oct 04 '22 18:10

Joel Cornett