Get list of attributes from list of objects?

Ian Kelly ian.g.kelly at gmail.com
Wed Aug 2 14:50:31 EDT 2017


On Wed, Aug 2, 2017 at 11:49 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Aug 3, 2017 at 3:21 AM, Ian Pilcher <arequipeno at gmail.com> wrote:
>> Given a list of objects that all have a particular attribute, is there
>> a simple way to get a list of those attributes?
>>
>> In other words:
>>
>>   class Foo(object):
>>       def __init__(self, name):
>>           self.name = name
>>
>>   foolist = [ Foo('a'), Foo('b'), Foo('c') ]
>>
>>   namelist = []
>>   for foo in foolist:
>>       namelist.append(foo.name)
>>
>> Is there a way to avoid the for loop and create 'namelist' with a single
>> expression?
>
> You can't eliminate the loop

Well, you can do this:

namelist = list(map(operator.attrgetter('name'), foolist))

But use what Chris and Terry suggested; it's cleaner.



More information about the Python-list mailing list