[Tutor] Should this be a list comprehension or something?

Tony Meyer tameyer at ihug.co.nz
Wed Jan 26 05:00:15 CET 2005


> Well, you can do this with list comprehensions, yeah:
> 
> totalmass = sum([WaterObject.mass for WaterObject in WaterList])
> totaltemp = sum([WaterObject.mass * WaterObject.temp for 
> WaterObject in 
> WaterList]) / totalmass
> return Water(totalmass, totaltemp)
> 
> Doesn't seem that much more Pythonic to me. I find it about as 
> readable as your code, but someone who isn't used to list 
> comprehensions will find that weird-looking.

I would agree that it doesn't seem any more Pythonic.  I think either way is
fairly readable (being able to use 'sum' with list comps helps readability,
IMO).

[...]
> As for the cons, as I said, it may seem less readable than the 
> original version to the non-experienced; and chances are it's slower 
> than the original version since it has to iterate through 4 lists 
> instead of 2.

Timeit gives me 6.73 seconds for the original, 10.70 seconds for list comps,
and 10.98 for gen exps, so it does look like the original is certainly
faster.

=Tony.Meyer



More information about the Tutor mailing list