[Tutor] list comprehension problem

Emile van Sebille emile at fenx.com
Sat Jul 4 00:02:18 CEST 2009


On 7/3/2009 1:59 PM Chris Fuller said...
> 
> The problem with these list comprehensions is that they have O(n**2) 
> complexity.  

But, the more you work with them the more ease you'll develop at 
understanding and deploying them.  I often find that a (quick) (perhaps 
complex) list comprehension is just what's needed vs a (less quick) 
(perhaps clarifying) refactoring.

> Whether they are faster or not depends on the speedup from the 
> list comprehension and the length of the input.  

I suspect that list comprehensions are invariably faster when analogous 
algorithms are used.  This doesn't mean it's the fastest way, only that 
they're faster than the same for loop.

> I'd be inclined to favor the linear for loop.

Yes, this one in particular gets slow quickly.  I generally find 
non-comprehension solutions easier to (re)understand the more complex 
they get.  OTOH, I've always had a passion for more compact code.  Blame 
it on the combined 8kb program and data memory footprint we had to 
operate in when I got started.

Emile



More information about the Tutor mailing list