[Tutor] list (in)comprehensions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 24 Jan 2001 13:19:24 -0800 (PST)


On Wed, 24 Jan 2001, kevin parks wrote:

> can't say it) C O M P R E H E N D them (ok i said it). What are list
> comprehensions good for, what do they make easier, how to use them,
> etc. As a guy who uses map and filter everyday, it seems like
> something i better know. I sorely wish there was a howto with code and
> someone talking to me too! (Python documentation shouldn't just be a
> screenshot of someone's interpreter, though including an interactive
> session is helpful).

List comprehensions make writing list-processing code a little
easier.  For example, let's say we had the list:

    L = list(range(20))          # [0, 1, ..., 19]

What sort of things can we do with it?  If we wanted to square each
number, we could do this:

    squaredL = map(lambda x: x * x, L)

But many people feel uncomforable about lambdas and maps.  List
comprehensions is 'map' in another disguise:

    squaredL = [x*x for x in L]

Here, we just tell Python the expression we want to compute, over some
sort of loop over a list.  For people that know about for loops, this
seems to be easier to handle than mapping a function across a list.  
Also, it reduces the need to use lambda.  (Not that lambda is a bad thing,
but it's initially weird to people.)

Hope this helps!