Lisp mentality vs. Python mentality

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Apr 26 08:56:38 CEST 2009


On Sun, 26 Apr 2009 08:52:30 +0300, Ciprian Dorin, Craciun wrote:

>     I liked very much your implementation for the compare function, it
> is very short and at the same time readable:
> 
>> def compare(a, b, comp=operator.eq):
>>     return (len(a) == len(b)) and all(comp(*t) for t in zip(a, b))
> 
>     But I have only one problem, it is suboptimal, in the sense that: *
>     it constructs two intermediary lists (the list comprehension and
> the zip call);

If you look closely, there is no list comprehension. The argument to 
all() is a generator expression, which does not construct an intermediary 
list.

However, you are right that zip produces a list, at least in Python 2.x. 
In Python 3 it produces a generator-like object.



>     * it evaluates all the elements, even if one is false at the
>     beginning;

No, all() uses short-cut evaluation. It will return as soon as it hits a 
False element.



>     So, could you overcome these problems?

In Python 2.4 or better, I can remove the intermediate list produced by 
zip with one line:

from itertools import izip as zip

(This may even work in 2.3, but I don't have 2.3 to test it.)


-- 
Steven



More information about the Python-list mailing list