Class object attributes to list in a one liner

Question:

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']

Many Thanks in advance

Asked By: Merithor

||

Answers:

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)

Answered By: jsbueno
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.