[Tutor] Python Cookbook

alan.gauld@bt.com alan.gauld@bt.com
Mon, 26 Aug 2002 14:03:31 +0100


> I understood what map() and filter() do, but why are list 
> comprehensions better?  

'Better' is a subjective term in most cases.
Comprehensions do have a couple of advantages:

1) consistency, the one construct can do all that map.filter etc do

2) there are some things that you can do with comprehensions 
that are either impossible or very cumbersome using map/filter etc.

>    map(function, alist)
> 
> can be better written using list comprehension as
> 
>    [function(x) for x in alist]

I'm not sure I agree that the LC is better here, personally 
I think map is easier to read and understand(I nearly said 
comprehend! :-) but certainly they both do the same job 
and, I suspect, have virtually identical performance.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld