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

Chris Angelico rosuav at gmail.com
Mon Mar 24 15:22:28 EDT 2014


On Tue, Mar 25, 2014 at 5:58 AM, Mark H Harris <harrismh777 at gmail.com> wrote:
> Its there, but its not on the built-ins; ie., you have to import it.  The
> confusion: why reduce, why not filter, nor map?  {rhetorical}

In other languages with those three, and without list/array
comprehensions, I've used filter occasionally and map reasonably
often, but I don't remember the last time I used reduce. Actually,
Pike has special syntax that can take the place of map sometimes, so I
might use filter more often than map in Pike code, because these don't
need explicit map calls:

//Suppose that clients is an array of connected clients on some server
clients->sockets->write("System message: blah blah blah\n");

Indexing an array (the -> is like Python's . as Pike's . is resolved
at compile time) produces an array, effectively mapping the elements
through "lambda x: x->sockets" and ditto for "->write". Calling an
array calls all the non-empty elements in it, with the same
argument(s), and produces an array of return values. (In this case, I
don't care about the return values, which will simply be the number of
bytes written to each socket. If there's a problem, it'll throw an
exception.) Huh. Even with that, and the [*] automap syntax, and such,
I still use map far more often than filter... and filter orders of
magnitude more often than reduce.

Aside: You'll often hear people talking about "map-reduce" with big
data. Python supports that. Look!

>>> map.__reduce__
<method '__reduce__' of 'map' objects>

Oh wait, that's nothing to do with reduce()...

*ducks for cover*

ChrisA



More information about the Python-list mailing list