# Nested for loop in generator

**URL:** <https://discourse.julialang.org/t/nested-for-loop-in-generator/78222>\
**Category:** General Usage\
**Tags:** question, potential-bug\
**Created:** [March 21, 2022, 3:18pm UTC](https://discourse.julialang.org/t/nested-for-loop-in-generator/78222 "2022-03-21T15:18:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![joh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/joh/32/34773_2.png) [@joh](https://discourse.julialang.org/u/joh)\
**Post date:** [March 21, 2022, 3:18pm UTC](https://discourse.julialang.org/t/nested-for-loop-in-generator/78222/1 "2022-03-21T15:18:18Z")

</div>

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

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

```

is the same as

```julia
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.

---

<div class="post-metadata">

**Author:** ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)\
**Post date:** [March 21, 2022, 3:32pm UTC](https://discourse.julialang.org/t/nested-for-loop-in-generator/78222/2 "2022-03-21T15:32:30Z")

</div>

It is intended. [The corresponding section of the manual](https://docs.julialang.org/en/v1/manual/arrays/#Generator-Expressions) 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.

---

<div class="post-metadata">

**Author:** ![joh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/joh/32/34773_2.png) [@joh](https://discourse.julialang.org/u/joh)\
**Post date:** [March 21, 2022, 3:47pm UTC](https://discourse.julialang.org/t/nested-for-loop-in-generator/78222/3 "2022-03-21T15:47:00Z")

</div>

Thanks, that’s good to know!
