python2.4 generator expression > python2.3 list expression

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Feb 21 02:50:20 EST 2005


snacktime wrote:
> I need to convert a generator expression to a list expression so it
> will work under python 2.3.
> 
> I rewrote this:
> 
> for c in range(128):
>   even_odd = (sum(bool(c & 1<<b) for b in range(8))) & 1
> 
> As this:
> 
> for c in range(128):
>   bo = [bool(c & 1<<b) for b in range(8)]
>   even_odd = sum(bo) & 1
> 
> 
> Seems to work, is there a better way to do this?

If you want to keep it as a generator that doesn't build a list
in memory, you can use itertools:

import itertools

for c in range(128):
     def _even_odd_func(b): return bool(c & 1<<b)
     even_odd = (sum(itertools.imap(_even_odd_func, xrange(8)))) & 1

The fact that you used range() instead of xrange() indicates that
you may not care about this, though. ;-)
-- 
Michael Hoffman



More information about the Python-list mailing list