simultaneous assignment

Steve R. Hastings steve at hastings.org
Tue May 2 15:35:16 EDT 2006


On Tue, 02 May 2006 19:11:36 +0000, John Salerno wrote:

> Grant Edwards wrote:
> 
>> Python knows how to count.  :)
>> 
>> def countFalse(seq):
>>     return len([v for v in seq if not v])
>> 
>> def countTrue(seq):
>>     return len([v for v in seq if v])
>> 
>> def truth_test(seq):
>>     return countTrue(seq) == 1
> 
> Gosh, so much to learn! Of course, I already know all about list 
> comprehensions, but now I just need to learn to *use* them! :)

Play around with them.  They are fun. :-)


We could also use "generator expressions", available only in
Python 2.4 and newer.

A list comprehension always builds a list.  A generator expression can
return values one at a time.

[v for v in seq if v]  # builds a list and returns it
(v for v in seq if v)  # returns a generator object

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


The generator expression saves Python from having to build a list and then
destroy the list.  It's useful when you only care about the *values* and
you don't want to save the list.

For a short list, the savings are small; but for a really large list, a
generator expression can save a lot of wasted effort in building the new
list and destroying it.


Python 2.5 will be introducing two new functions, "all()" and "any()",
which are intended for use mostly with generator expressions:

any(v for v in seq if v)  # true if any v evaluates true
all(v for v in seq if v)  # true if *all* v evalute true


Or a better example:

any(is_green(x) for x in lst)  # true if any value in list is green

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




More information about the Python-list mailing list