Nested for loop in generator

I’ve just stumbled across something odd when using a nested for statement in a generator expression. I would have expected collect((n,k) for n in 1:5, k in 1:n) to be equivalent to collect((n,k) for n in 1:5 for k in 1:n), just like

for n in 1:5, k in 1:n
    ...
end

is the same as

for n in 1:5
    for k in 1:n
        ...
    end
end

Instead, the single for statement produces the full 5x5 matrix of (n,k) combinations (equivalent to collect((n,k) for n in 1:5, k in 1:5)) whereas the explicit double for statement produces only the pairs with k <= n (as expected).
Am I missing something here? I this done on purpose or a bug? I don’t find the behavior very intuitive. This is using Julia 1.7.1.

It is intended. The corresponding section of the manual describes this behavior, you could have checked there.

I agree that the difference in notation is small and, therefore, easy to miss or to employ without intention. However, the analogy with the for does not make much sense: a for loop do not define a shape per se, and you did not include in your examples if a dummy a object is being indexed as a[k, n] or a[k + (n-1)*5]. The generator expression describes a collection/object that did not exist before, it needs a way to express the shape the generated values are organized.

Thanks, that’s good to know!

1 Like