Get index in the list of objects by attribute in Python

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)