generated comprehensions

Greg Ewing greg at cosc.canterbury.ac.nz
Tue May 14 22:27:03 EDT 2002


Garth T Kidd wrote:
> 
>     def printOdds(upto):
>         for odd in [num for num in xrange(upto) if num%2]:
>             print odd
> 
> ... works fine if upto is 5, but just sits there chewing up memory if
> upto is 10**9, at which point you abandon comprehensions and do it
> properly:

I don't think I would have used a comprehension there in
the first place, because building a list isn't needed.
i.e. I would have "done it properly" the first time,
particularly since the comprehension only saves 2 lines
of code.

> I'm sure I'll figure out a decent rule of thumb (say, "unit test with
> the biggest practical number, and get rid of comprehensions if they
> turn out to be a problem", or "don't use comprehensions with
> generators"),

The rule of thumb you want is: If you need the result as
a list, use a comprehension, otherwise don't.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list