1

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I am almost sure I tried this way and it gave me an other outcome but now it works.
2

The numbers below 4 in L1 are:

L1_below_4 = [x for x in L1 if x < 4]

And for L2:

L2_below_4 = [y for y in L2 if y < 4]

Now it's easy:

[[x + y for x in L1_below_4] for y in L2_below_4]

Or as a one-liner:

[[x + y for x in L1 if x < 4] for y in L2 if y < 4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.