List comprehension returning subclassed list type?

bullockbefriending bard kinch1967 at
Sun Mar 25 11:34:41 CEST 2007

Thanks! I went with extend and generator expression as I *am* dealing
with rather a lot of data. Now I think I'm going to go on a little
hunt through my code looking for more places where I should replace
list comprehensions with generator expressions - bit of a newbie here.

On Mar 25, 3:57 pm, Steven D'Aprano
<s... at> wrote:
> On Sat, 24 Mar 2007 23:43:10 -0700, bullockbefriending bard wrote:
> > 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.
> List comprehensions give you a list. If you want to convert that list into
> the type of z_list, you need to do it yourself. Since ZList sub-classes
> from list, probably the easiest way is just:
> z_list = ZList([some list comprehension here])
> > I could, of course go and write a static method in
> > ZList which takes a plain list of Z objects and returns a ZList.
> Yes, that would be one such way. Another way is:
> z_list.extend([some list comprehension here])
> If you are using a recent enough version of Python, you probably don't
> even need the list comprehension. Just use a generator expression:
> z_list.extend(Z(y.var1, y.var2,..) for y in list_of_objects_of_class_Y)
> That's especially useful if the list of objects is huge, because it avoids
> creating the list twice: once in the list comp, and once as z_list.
> --
> Steven.

More information about the Python-list mailing list