0

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

Merithor
  • 70
  • 5
  • 1
    Ignoring the incorrect syntax of your example, are you aware of list comprehensions? Something like `my_new_list = [o.name for o in my_object_list]`. – chepner Nov 17 '22 at 16:11
  • @chepner That was exactly what I was looking for, would you post it as an answer? Then I could mark it as correct. – Merithor Nov 17 '22 at 16:21

1 Answers1

0

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)

jsbueno
  • 99,910
  • 10
  • 151
  • 209