List comprehension returning subclassed list type?

Pierre Quentel quentel.pierre at wanadoo.fr
Sun Mar 25 03:03:52 EDT 2007


On 25 mar, 08:43, "bullockbefriending bard" <kinch1... at gmail.com>
wrote:
> Given:
>
> class Z(object):
>     various defs, etc.
>
> class ZList(list):
>     various defs, etc.
>
> i would like to be able to replace
>
> z_list = ZList()
> for y in list_of_objects_of_class_Y:
>     z_list.append(y)
>
> with something like this:
>
> z_list = [Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y]
>
> Of course this just gives me a plain list and no access to the
> methodsof z_list. I could, of course go and write a static method in
> ZList which takes a plain list of Z objects and returns a ZList.
>
> Anyway, my question is whether or not this can be done more elegantly
> via list comprehension?

Hello,

A list comprehension will give you a list. But you can use a generator
expression :

z_list = ZList(Z(y.var1, y.var2,..)
    for y in list_of_objects_of_class_Y)

Regards,
Pierre




More information about the Python-list mailing list