Lisp mentality vs. Python mentality

Tim Chase python.list at tim.thechases.com
Sun Apr 26 08:14:06 EDT 2009


>     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);
>     * it evaluates all the elements, even if one is false at the beginning;
> 
>     So, could you overcome these problems?

The solution would be to use itertools.izip() instead of the 
stock zip().  The all() function short-circuits at the first 
non-True value.  Thus, using izip() instead will (1) not create 
any new lists (it's a generator, not a list) and (2) the all() 
will only look until it fails.

Just make sure that your comp() function returns equality for 
this to work, or otherwise use "not comp()" (which is germane if 
you use a __cmp__ function that returns 0 for equality)

-tkc





More information about the Python-list mailing list