Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 22 10:46:01 CET 2014

On Fri, 21 Mar 2014 23:51:38 -0500, Mark H Harris wrote:

> Lambda is a problem, if only because it causes confusion. What's the
> problem?  Glad you asked. The constructs DO NOT work the way most people
> would expect them to, having limited knowledge of python!

Why is that a problem? Would you consider it a problem that people who 
don't understand BASIC can't understand BASIC? ("I don't get the 
difference between GOTO and GOSUB. Obviously GOSUB is a problem and 
should be throw out.") Do you think that the fact that people who have 
never used a TI-89 calculator before may have trouble used a TI-89 
calculator means that TI-89 calculators are "a problem"? (I've taught 
school children who didn't know how to use their calculator.)

The problem is ignorance, not the calculator, and not lambda.

You've told us that "most people" (which people? dentists? lawyers? 
illiterate tribesmen from the Amazon? professional programmers?) are 
surprised by lamba's behaviour, but you haven't actually told us what 
behaviour is surprising, or what "most people" expect lambda to do. 
Perhaps you ought to?

> I ran into
> this thing about seven years ago (when I was studying Haskell, and
> Scheme) and I wanted to see how "pure functional" python was (well, not
> at all really).

Python is not a pure functional language, but you can write functional 
code in it. If you want a pure functional language, you know where to 
find one.

(I wonder whether, say, Haskell has the people coming along and demanding 
that it should become more like Python?)

> I can see uses for python's lambda.  But, honestly, I think python could
> deprecate its use and in five years just remove it from the language;
> along with filter, map, and reduce !

Python could deprecate many things. It would make Python a worse language.

By the way, are you aware that lambda is *identical* to def except for 
three things?

- lambda is an expression, not a statement like def;

- the body of a function created with lambda is limited to a 
  single expression, not a block;

- the function object created with lambda has a generic name.

So unless the surprising behaviour about lambda that you're about to tell 
us about relates to one of those three things, I *guarantee* that 
functions created with def have the same surprising behaviour.

Steven D'Aprano

More information about the Python-list mailing list