I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.
Is there any built-in functions to do that?
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
A list comprehension would work just fine:
[o.my_attr for o in my_list]
But there is a combination of built-in functions, since you ask :-)
from operator import attrgetter map(attrgetter('my_attr'), my_list)
are you looking for something like this?
[o.specific_attr for o in objects]
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