# Iterator flatten with nested tuples

I am trying to flatten the following Iterator:

``````julia> it=Iterators.product(1:3,1:4); collect(it)
3×4 Matrix{Tuple{Int64, Int64}}:
(1, 1)  (1, 2)  (1, 3)  (1, 4)
(2, 1)  (2, 2)  (2, 3)  (2, 4)
(3, 1)  (3, 2)  (3, 3)  (3, 4)
``````

and hope to get an length 12 iterator that yields a pair of indices a time. However, `Iterators.flatten(it)` returns a length 24 iterator that yields one index a time:

``````julia> collect(Iterators.flatten(it))
24-element Vector{Int64}:
1
1
2
...
``````

So how to generate the effect of two indices at a time? I’m looking for an `iterator` that yields these pairs.

If you don’t need the product, maybe this is what you can use:

``````julia> it = ( (i,j) for j in 1:4 for i in 1:3 )
Base.Iterators.Flatten{Base.Generator{UnitRange{Int64}, var"#22#23"}}(Base.Generator{UnitRange{Int64}, var"#22#23"}(var"#22#23"(), 1:4))

julia> collect(it)
12-element Vector{Tuple{Int64, Int64}}:
(1, 1)
(2, 1)
(3, 1)
(1, 2)
(2, 2)
(3, 2)
(1, 3)
(2, 3)
(3, 3)
(1, 4)
(2, 4)
(3, 4)
``````

Did not realize the extra `for` instead of a `,` to have a flattening effect. Thank you!

Another way is to shield ` it` inside ` Ref()` or in a tuple:

``````collect(Iterators.flatten((it,)))
``````
2 Likes