computing a weighted sum

Steven Bethard steven.bethard at gmail.com
Wed Mar 16 11:20:05 EST 2005


Will McGugan wrote:
> In Python 2.3
> 
> sum( [ _x * _w for _x, _w in zip( x, w ) ] )
> 
> or in 2.4
> 
> sum( _x * _w for _x, _w in zip( x, w ) )

Any reason for the leading underscores?  If you're trying to avoid 
polluting your namespace, you should note that generator expressions 
don't leak their loop variables, so you can write the second as:

sum(x*w for x, w in zip(x, w))

without any worries of overwriting x and w.  (Of course I would probably 
name them something different anyway, e.g. x_item and w_item...)

STeVe



More information about the Python-list mailing list