simultaneous assignment

Steve R. Hastings steve at hastings.org
Wed May 3 00:02:15 EDT 2006


On Tue, 02 May 2006 21:44:21 +0200, Boris Borcic wrote:
> note that generators have no defined length - precisely because they feed
> values one at a time while you need them all together to speak of a
> length. The second expression will raise a TypeError because of that.

Er, yes.  If I had actually run that code, I would have seen that error.

Thank you for the correction.


> If you want to count objects 
> with a generator expression, use
> 
> sum(1 for v in seq if some_condition(v))
> 
> which is also clearer imho; summing ones for each item satisfying a
> condition - isn't that a definition of counting ?

That is indeed very clear and I like it.

You could also use a function that counts all different values in a list,
reducing the list to a dictionary whose keys are the unique values from
the list.  I got the idea from a discussion here on comp.lang.python; I
called my version of it tally().

d = tally(bool(x) for x in seq)
print d[True]  # prints how many true values in seq
print d[False]  # prints how many false values in seq


tally() is in my iterwrap.py module, which you can get here:

http://home.blarg.net/~steveha/iterwrap.tar.gz

-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list