# Too many levels of nested for loops

**URL:** <https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335>\
**Category:** General Usage\
**Created:** [March 2, 2021, 2:32pm UTC](https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335 "2021-03-02T14:32:17Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![greatpet](https://avatars.discourse-cdn.com/v4/letter/g/e495f1/32.png) [@greatpet](https://discourse.julialang.org/u/greatpet)\
**Post date:** [March 2, 2021, 2:32pm UTC](https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335/1 "2021-03-02T14:32:17Z")

</div>

Is there a more pretty way to rewrite the code below, without performance penalties?

```
sum = 0
for i1 in 1:4
    for i2 in 1:4
        for i3 in 1:4
            for i4 in 1:4
                sum += some_function(i1, i2, i3, i4)
            end
        end
    end
end

```

My actual code has even more levels (six) of nesting. This big triangle shape is an eyesore!

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [March 2, 2021, 2:34pm UTC](https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335/2 "2021-03-02T14:34:51Z")

</div>

```julia
julia> s = 0
       for i1=1:4, i2=1:4, i3=1:4, i4=1:4
          s += i1 + i2 + i3 + i4
       end
       s
2560

julia> s = 0
       for i1 in 1:4,
           i2 in 1:4,
           i3 in 1:4,
           i4 in 1:4
         s += i1 + i2 + i3 + i4
       end
       s
 2560

```

---

<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 2, 2021, 2:40pm UTC](https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335/3 "2021-03-02T14:40:31Z")

</div>

If you need even more power (i.e., do this nested loop over an array of ranges instead of a fixed number of them) you probably can use [`Combinatorics.jl`](https://github.com/JuliaMath/Combinatorics.jl).

---

<div class="post-metadata">

**Author:** ![MarcMush](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marcmush/32/18006_2.png) [@MarcMush](https://discourse.julialang.org/u/MarcMush)\
**Post date:** [March 4, 2021, 3:14pm UTC](https://discourse.julialang.org/t/too-many-levels-of-nested-for-loops/56335/4 "2021-03-04T15:14:04Z")

</div>

you can use `Iterators.product`:

```julia
s = 0
for (i1,i2,i3,i4) in Iterators.product(1:4, 1:4, 1:4, 1:4)
    s += i1 + i2 + i3 + i4
end
s

```

or with an arbitrary number of nested loops:

```julia
N = 4
s = 0
for i in Iterators.product(fill(1:4, N)...)
    s += sum(i)
end
s

```
