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 04:32:13 CET 2014

On Mon, Mar 24, 2014 at 1:35 PM, Rhodri James <rhodri at wildebst.org.uk> wrote:
> I'm not sure I would.  I look at that line of code and think of it as
> "Create a list...", very much in an imperative manner.  Then again, compared
> with C structs and typedefs and actual honest-to-God type declarations,
> there's precious little in Python I would consider truly declarative.

By the way: Python does have a difference between "declarative" and

def f(): # Imperative
    global x # Declarative
    x += 1 # Imperative

Declaratives control things, imperatives become byte code. Everything
in the byte code is imperative. "LOAD_GLOBAL" means "fetch this global
and put it on the stack". "INPLACE_ADD" means "iadd the top two stack
elements and push the result onto the stack". "STORE_GLOBAL" means
"pop the top stack element and store it in this global". Very very
imperative, and there's none of that created by the "global"
statement. So in that sense, yes, "x = [1, 2, 3]" is imperative; it
loads three constants, builds a list, and stores it. But digging into
the byte code isn't really helpful; it's much more useful to look at
the source code and how the programmer thinks about it.


More information about the Python-list mailing list