Create nested list using list comprehension
<p>I have two lists:</p>

<pre><code>L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]
</code></pre>

<p>And I need to create sub-list for each item in L2 that is smaller than 4, add it to all the numbers in L1 that are smaller than 4.
I tried doing this:</p>

<pre><code>result = [(x+y) for x in L2 if x &lt; 4 for y in L1 if y &lt; 4]
</code></pre>

<p>But it resulted me this:</p>

<pre><code>[4, 4, 6, 6, 6, 6]
</code></pre>

<p>While the outcome should look like this:</p>

<pre><code>[[4, 4], [6, 6], [6, 6]]
</code></pre>

<p>any idea on how should I nest it in the right way?</p>

<p>Create a nested list comprehension </p>

<pre><code>&gt;&gt;&gt; [[(x+y) for y in L1 if y &lt; 4] for x in L2 if x &lt; 4]
[[4, 4], [6, 6], [6, 6]]
</code></pre>

<p>Here the inner list comprehension creates the inner lists which are then appended to a single list by the outer comprehension. </p>

python list list-comprehension nested-lists