Get list of attributes from list of objects?
Terry Reedy
tjreedy at udel.edu
Wed Aug 2 14:01:14 EDT 2017
On 8/2/2017 1:21 PM, Ian Pilcher 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?
namelist = [foo.name for foo in foolist]
--
Terry Jan Reedy
More information about the Python-list
mailing list