473,657 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List comprehension returning subclassed list type?

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?

Mar 25 '07 #1
4 1563
To the best of my understanding, this answers your question:

iterable
A container object capable of returning its members one at a
time. Examples of iterables include all sequence types (such as
list, str, and tuple) and some non-sequence types like dict and
file and objects of any classes you define with an __iter__()
or __getitem__() method. Iterables can be used in a for loop
and in many other places where a sequence is needed (zip(),
map(), ...). When an iterable object is passed as an argument
to the builtin function iter(), it returns an iterator for the
object. This iterator is good for one pass over the set of
values. When using iterables, it is usually not necessary to
call iter() or deal with iterator objects yourself. The for
statement does that automatically for you, creating a temporary
unnamed variable to hold the iterator for the duration of the
loop. See also iterator, sequence, and generator.
bullockbefriend ing bard 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?

--
Shane Geiger
IT Director
National Council on Economic Education
sg*****@ncee.ne t | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
Mar 25 '07 #2
On 25 mar, 08:43, "bullockbefrien ding bard" <kinch1...@gmai l.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

Mar 25 '07 #3
On Sat, 24 Mar 2007 23:43:10 -0700, bullockbefriend ing 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.

Mar 25 '07 #4
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...@REMOVE.TH IS.cybersource. com.auwrote:
On Sat, 24 Mar 2007 23:43:10 -0700, bullockbefriend ing 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.

Mar 25 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
3342
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I see that generator expressions have been added to the language with 2.4 and I question the need for it. I know that it allows for lazy evaluation which speeds things up for larger lists but why was it necessary to add it instead of improving list...
6
1968
by: jena | last post by:
hello, when i create list of lambdas: l=] then l() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=]
6
2161
by: Heiko Wundram | last post by:
Hi all! The following PEP tries to make the case for a slight unification of for statement and list comprehension syntax. Comments appreciated, including on the sample implementation. === PEP: xxx Title: Unification of for-statement and list-comprehension syntax
4
1808
by: Gregory Guthrie | last post by:
Sorry for a simple question- but I don't understand how to parse this use of a list comprehension. The "or" clauses are odd to me. It also seems like it is being overly clever (?) in using a lc expression as a for loop to drive the recursion. Thanks for any insight! Gregory
19
1736
by: bvdp | last post by:
Please help my poor brain :) Every time I try to do a list comprehension I find I just don't comprehend ... Anyway, I have the following bit of code: seq = tmp = for a in range(len(seq)): tmp.extend(*seq)
6
1999
by: fdu.xiaojf | last post by:
Hi all, I can use list comprehension to create list quickly. So I expected that I can created tuple quickly with the same syntax. But I found that the same syntax will get a generator, not a tuple. Here is my example: In : a = (i for i in range(10)) In : b =
1
1099
by: Shane Lillie | last post by:
I've got a bit of code that looks like this: for i in xrange(1000): # shuffle the doors doors = random.shuffle(doors) # save the doors that have goats (by index) goats = == 'G' ]
0
1787
by: Hatem Nassrat | last post by:
on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote: Well I have looked into this and it seems that using the list comprehension is faster, which is reasonable since generators require iteration and stop iteration and what not.
5
1082
by: Pat | last post by:
I have written chunks of Python code that look this: new_array = for a in array: if not len( a ): continue new_array.append( a ) and...
0
8316
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8833
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8737
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6174
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5636
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4168
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1730
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.