I have a list of objects and I'm trying to get one object's index in that list from an attribute of the object I have (e.g. name). Similar to something like the example below:
class Employee:
def __init__(self, name):
self.name = name
def add_emp(name):
employees.append(Employee(name))
employees = []
add_emp('Emp1')
Now I'm trying to get the index of 'Emp1' in the list self.employees (here '0'). I tried this here:
print(employees.index(filter(lambda x: x.name == 'Emp1', employees)))
but he tells me that 'ValueError: < filter object at 0xblabla > is not in list'. What do I have to change or is there a better option to handle this?
Well don't search for the filter itself, search for what the filter finds. For example, next(filter(...))
instead of filter(...)
.
But really better just use enumerate
:
print(next(i for i, x in enumerate(employees) if x.name == 'Emp1'))
Or you could create a list of names and ask that for the index:
print([x.name for x in employees].index('Emp1'))
It's less efficient, though.
Because filter()
returns a filter object, an approach would be converting it to a list and take the element with index 0:
print(employees.index(list(filter(lambda x: x.name == 'Emp1', employees))[0]))
But, the best approach would be using enumerate()
:
def get_employee_index(name):
for i, e in enumerate(employees):
if e.name == name:
return i
return -1 # for not found employee
Output:
>>> get_employee_index('Emp1')
0
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