pythonlist-comprehension

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

[ (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