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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With