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:57:19 EDT 2014


On Tue, Mar 25, 2014 at 6:42 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Mon, Mar 24, 2014 at 1:12 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> Incidentally, I've often modified my loop counter, in C or REXX or any
>> other language. About the only situation where I actually miss it in
>> Python, though, is iterating over a list and mutating the list on the
>> way through; and even that can often be done in other ways (maybe a
>> list comp, filtering out some of the elements?). It's amazing how
>> something can be so utterly fundamental (I mean, come ON! Who can
>> imagine a language with no equivalent of the basic "do i=1 to 10"
>> (REXX) or "for (int i=0;i<10;++i)" (C++) loop???) and yet so
>> dispensable.
>
> I'm not sure "fundamental" is the right word.  A for loop is just a
> while loop with some syntactic sugar.  For that matter, a while loop
> is just a structured goto...

Of course, and function calls are just stack operations and gotos too.
That's not what makes it fundamental - I'm talking at a source code
level. Can you imagine a high level language without a simple notation
for variable assignment? Certainly not. [1] Variable assignment, name
binding, whatever you call it, is fundamental. Some kind of structured
looping is also pretty critical; you don't see languages that force
you to use bare goto everywhere and call themselves "high level". [2]
Every high level language also needs some way to iterate over numbers.
Most of them provide it as an intrinsic; Python happens to do it as a
foreach over an easily-constructed iterable.

ChrisA

[1] DeScribe Macro Language would borderline-fail this test if I
called it a HLL. It has "SET something TO somevalue". But DML is about
on the level of Python's "dis.dis" output - assembly language for a
byte-code interpreter.
[2] DML passes this test, even. It has a block IF/ELSE/END IF
statement, and a REPEAT/END REPEAT for looping, with the loop
condition being provided by a statement "EXIT WHEN condition" that's
like Python's "if condition: break". Mind you, it also provides
language-level support for message boxes, including prompt boxes (ask
the user to provide a string or integer), so it's a bit of an odd
duck.



More information about the Python-list mailing list