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

Marko Rauhamaa marko at pacujo.net
Mon Mar 24 13:36:48 CET 2014

Chris Angelico <rosuav at gmail.com>:

> 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)

I still prefer the "def" variant. It even allows you to clarify the
meaning of the tuple slot by using a nicer name.


More information about the Python-list mailing list