simultaneous assignment

Boris Borcic bborcic at gmail.com
Tue May 2 15:44:21 EDT 2006


Steve R. Hastings wrote:

> len([v for v in seq if v])  # builds a list, then feeds it to len()
> len(v for v in seq if v)  # gen obj feeds values to len one at a time

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. 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 ?



More information about the Python-list mailing list