How can I make a nested list comprehension where the inner iterator depends on the outer one?
Using a for loop, I can do
res = []
for y in 1:5, x in 1:y
push!(res, x*y)
end
but I would like to accomplish the same using an expression like [x*y for x in 1:y, y in 1:5]
, if possible.
Edit: I just figured out
vcat([[x*y for x in 1:y] for y in 1:5]...)
although my understanding is that splatting is to be avoided if possible.
1 Like
This gives the same result
[x*y for y in 1:5 for x in 1:y]
2 Likes
Thank you. I was stuck because I didn’t expect to have to move the inner iterator to the outside.
I guess the justification for this design is that this puts the x
and y
iterators in the same order as the equivalent for loop. Is this compatibility principle consistent across languages? I checked and Python works like Julia in this regard:
In [2]: [x*y for y in range(5) for x in range(y)]
Out[2]: [0, 0, 2, 0, 3, 6, 0, 4, 8, 12]
1 Like