# How do you make an arbitrarily nested for loop?

**URL:** <https://discourse.julialang.org/t/how-do-you-make-an-arbitrarily-nested-for-loop/88225>\
**Category:** General Usage\
**Tags:** question, metaprogramming, loops\
**Created:** [October 4, 2022, 11:28am UTC](https://discourse.julialang.org/t/how-do-you-make-an-arbitrarily-nested-for-loop/88225 "2022-10-04T11:28:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![AwesomeQuest](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/awesomequest/32/38910_2.png) [@AwesomeQuest](https://discourse.julialang.org/u/AwesomeQuest)\
**Post date:** [October 4, 2022, 11:28am UTC](https://discourse.julialang.org/t/how-do-you-make-an-arbitrarily-nested-for-loop/88225/1 "2022-10-04T11:28:40Z")

</div>

Say you have an array of ranges `rngs = [10:-1:0, 10:-4:2, 10:-3:1]`.  
How would you make a nested loop equivalent to

```julia
inds = zeros(length(rngs))
for inds[1] in rngs[1], inds[2] in rngs[2], inds[3] in rngs[3]

```

But for an arbitrary array of ranges?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [October 4, 2022, 11:49am UTC](https://discourse.julialang.org/t/how-do-you-make-an-arbitrarily-nested-for-loop/88225/2 "2022-10-04T11:49:28Z")

</div>

Use a tuple of ranges with [`CartesianIndices`](https://docs.julialang.org/en/v1/base/arrays/#Base.IteratorsMD.CartesianIndices):

```julia
rngs = (10:-1:0, 10:-4:2, 10:-3:1)
for i in CartesianIndices(rngs)
    inds = Tuple(i)
    @show inds
end

```

(You ideally want a tuple and not an array for this sort of thing, because you want the length — i.e., the number of nested loops — to be known to the compiler.)

---

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [October 4, 2022, 12:39pm UTC](https://discourse.julialang.org/t/how-do-you-make-an-arbitrarily-nested-for-loop/88225/3 "2022-10-04T12:39:10Z")

</div>

Another way would be to loop over this iterator

```julia
Iterators.product(rngs...)

```
