Reading List Comprehension?

Remco Gerlich scarblac-spamtrap at
Thu Sep 7 10:53:54 CEST 2000

Stephen Hansen wrote in comp.lang.python:
> But..list comprehensions.. I can't quite fathom.
> --> x for subseq in seq for x in subseq
> Eh?!?! That looks so..wrong. No whitespace, parens, no nothing, with
> all those keywords mixed in there. I can't pronounce it, or make any
> sense outat it. Maybe that's because the examples insisted upon using
> exponential syntax, instead of something simple like addition. :)

This one is a bit weird, flattening a list. It makes a list of all the
elements inside a list of lists.

l = [x for subseq in seq for x in subseq]

is equivalent to

l = []
for subseq in seq:
   for element in subseq:
> I don't know -- is there a more in depth, vastly basic, tutorial to
> what the heck these things are somewhere? It,
> not-at-all-like-Python.

I'm also still uncomfortable with those "double" comprehension (from a list
of lists). Somehow I feel that those two for clauses should have been the
other way around.

I hope I will be able to use the simpler comprehension in place of most
lambda/map combinations:

Irritating constructs like
L = map(lambda x: expression, X)

L = [expression for x in X]

And: you don't get the namespace problems that the lambda has!!
(No arg=arg,l=l, etc like you sometimes need in lambdas).

def print_power():
   "Ask the user for an integer (n) and print 0^n, 1^n, ..., 10^n"
   power = input("Which power to print?")
   print map(lambda x,power=power: x**power, range(11))
   print [x**power for x in range(11)] 
I think the new notation is both shorter and easier to read. I don't
think I will be using the syntax with multiple fors a lot.
Remco Gerlich,  scarblac at

   This is no way to be
     Man ought to be free      -- Ted Bundy
       That man should be me

More information about the Python-list mailing list