BoooYaKa BoooYaKa - 2 months ago 13
Python Question

Create nested list using list comprehension

I have two lists:

L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]


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:

result = [(x+y) for x in L2 if x < 4 for y in L1 if y < 4]


But it resulted me this:

[4, 4, 6, 6, 6, 6]


While the outcome should look like this:

[[4, 4], [6, 6], [6, 6]]


any idea on how should I nest it in the right way?

Answer

Create a nested list comprehension

>>> [[(x+y) for y in L1 if y < 4] for x in L2 if x < 4]
[[4, 4], [6, 6], [6, 6]]

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