# For-loop over two arrays, sequentially

**URL:** <https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699>\
**Category:** General Usage\
**Created:** [May 26, 2022, 8:24am UTC](https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699 "2022-05-26T08:24:11Z")\
**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:** [May 26, 2022, 8:24am UTC](https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699/1 "2022-05-26T08:24:11Z")

</div>

I want to write code like this:

```julia
for i in vcat(vector1, vector2)
    do_something(i)
end

```

But I want to avoid the allocation of a new array in `vcat`. What’s a good way to do this?

---

<div class="post-metadata">

**Author:** ![lostella](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lostella/32/356_2.png) [@lostella](https://discourse.julialang.org/u/lostella)\
**Post date:** [May 26, 2022, 8:35am UTC](https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699/2 "2022-05-26T08:35:50Z")

</div>

```julia
for v in (v1, v2)
    for el in v
        do_something(el)
    end
end

```

---

<div class="post-metadata">

**Author:** ![lostella](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lostella/32/356_2.png) [@lostella](https://discourse.julialang.org/u/lostella)\
**Post date:** [May 26, 2022, 8:38am UTC](https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699/3 "2022-05-26T08:38:17Z")

</div>

Or use `Iterators.flatten`: [Iteration utilities · The Julia Language](https://docs.julialang.org/en/v1/base/iterators/#Base.Iterators.flatten)

```julia
for el in Iterators.flatten((v1, v2))
    do_something(el)
end

```

---

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [May 26, 2022, 9:18am UTC](https://discourse.julialang.org/t/for-loop-over-two-arrays-sequentially/81699/4 "2022-05-26T09:18:55Z")

</div>

FWIW, from [this related thread](https://discourse.julialang.org/t/iterating-over-two-vectors-with-vcat-is-faster-than-iterators-flatten-and-catviews/15698), `vcat` allocates but seems to be faster than `Iterators.flatten`.
