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)