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 12:49:38 CET 2014


On Mon, Mar 24, 2014 at 8:55 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Ian Kelly <ian.g.kelly at gmail.com>:
>
>> If lambda were going to be deprecated and removed then it already
>> would have happened in Python 3, because Guido tried to do precisely
>> that. I'm not sure what the reasons were for keeping it in the end
>> (according to PEP 3099 it was because nobody suggested a suitable
>> replacement), but if he couldn't get rid of it then, he never will.
>
> You never *need* (Python's) lambda for anything. Inner functions are
> more capable and almost always more readable. It doesn't hurt to have
> lambda, but I don't find any use for it, either.

They're often not more readable. A lot of people seem to equate
"verbose" with "readable", possibly by faulty extrapolation from
unreadably crunched code with one-letter variables and no line breaks.
But which of these is truly more readable?

squares = []
for n in range(30):
    squares.append(n * n)

squares = [n * n for n in range(30)]

Similarly, there are plenty of cases where a nameless function is MUCH
clearer than breaking it out into a separate def and then using the
name once. Do you name the function for what it does internally?

def get_oneth_element_index(item):
    return item[1].index
L.sort(key=get_oneth_element_index)

Or for how you're using it?

def keyfunc(item):
    return item[1].index
L.sort(key=keyfunc)

Or do you just shortcut the whole thing by inlining it?

L.sort(key=lambda item:item[1].index)

Hey look, that's weakref.py line 941 right there. (It happens to be
the alphabetically last use of lambda in the stdlib. Made a good
example, although it'd be more common to have a space after that
colon.)

ChrisA



More information about the Python-list mailing list