[Tutor] Getting list of attributes from list of objects

Serdar Tumgoren zstumgoren at gmail.com
Thu Sep 10 17:36:49 CEST 2009


> I have the following list
>
> l= [ a, b, c]
>
> Where a,b,c are objects created from one class, e.g. each has title
> attribute.
> What I want to have is a list of titles, e.g. [a.title, b.title, c.title]
>
> Is there a quick way to do it? Or I should use loops (looping through each
> element, and generating list)

I think a list comprehension might be the most compact way to
accomplish what you're after:

objcts = [a, b, c]

titles = [obj.title for obj in objcts]


More information about the Tutor mailing list