50

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?

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Janis Veinbergs
  • 6,977
  • 5
  • 46
  • 77

4 Answers4

81

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)
Jarret Hardie
  • 90,470
  • 10
  • 128
  • 124
10

are you looking for something like this?

[o.specific_attr for o in objects]
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
9

The first thing that came to my mind:

attrList = map(lambda x: x.attr, objectList)
Coffee on Mars
  • 978
  • 6
  • 19
1

Assuming you want field b for the objects in a list named objects do this:

[o.b for o in objects]
RossFabricant
  • 11,932
  • 3
  • 40
  • 51