fors in python list comprehension
<p>Consider I have nested for loop in python list comprehension</p>

<pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
&gt;&gt;&gt; [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
&gt;&gt;&gt; [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]
</code></pre>

<p>I can't explain why is that when i change the order of two <code>fors</code> </p>

<pre><code>for y in x
</code></pre>

<p>What's <code>x</code> in second list comprehension?</p>

<p>It's holding the value of the previous comprehsension. Try inverting them, you'll get an error</p>

<pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
&gt;&gt;&gt; [y for y in x for x in data]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'x' is not defined
</code></pre>

<p>To further test it out, print <code>x</code> and see </p>

<pre><code>&gt;&gt;&gt; [y for x in data for y in x]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
&gt;&gt;&gt; x
[6, 7, 8]
&gt;&gt;&gt; [y for y in x for x in data]
[6, 6, 6, 7, 7, 7, 8, 8, 8]
</code></pre>

python list python-2.7 for-loop list-comprehension