Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python list comprehension — two loops with three results?

I can ask my question best by just giving an example. Let’s say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this:

[ (y+z,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ]

This works, giving me

[(0, 0, 0), (3, 0, 3), (6, 0, 6), (9, 0, 9), (12, 0, 12), (15, 0, 15), ... ]

I am wondering, though, if there is a way to do it more cleanly, something to the effect of

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ (x,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ... somehow defining x(y,z) ... ]

I would consider something like this to be more clean, especially since what I really need to do is much more complicated than the example I give here. Everything I have tried has given me a syntax error.

>Solution :

You can do:

out = [
    (x, y, z)
    for y in range(10)
    if y % 2 == 0
    for z in range(20)
    if z % 3 == 0
    for x in [y + z]  # <-- initialize `x` in list-comprehension
]

This is optimized since Python 3.9: https://docs.python.org/3/whatsnew/3.9.html#optimizations

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading