Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class object attributes to list in a one liner

I have a list of class objects, e.g.:

child1 = Child(Name = 'Max', height = 5.1, weight = 100)
child2 = Child(Name = 'Mimi, height = 4.1, weight = 80)
my_object_list = [child1, child2]

Is there a way to create a new list dynamically with one similiar attribute of each object as a one liner? I know how to do it in a for loop, that’s why I am explicitely asking for a one liner.

desired result: my_new_list = ['Max', 'Mimi']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Many Thanks in advance

>Solution :

this kind of things is made easy by the comprehension syntax in Python;

my_new_list = [item.name for item in old_list]

Now, if one does not know at coding-time which attribute should be retrieved, the getattr built-in can be used to retrieve an attribute by name passed as a string:

attr = 'name'
my_new_list = [geattr(item, attr) for item in old_list]`

Or also, operator.attrgetter:

from operator import attrgetter

op = attrgetter("name")

new_list = [op(item) for item in old_list]
# and this looks pretty when used with "map" as well:

name_iterator = map(op, old_list)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading