# Most elegant way to fill an Array inside for loop?

**URL:** <https://discourse.julialang.org/t/most-elegant-way-to-fill-an-array-inside-for-loop/46914>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [September 19, 2020, 1:59pm UTC](https://discourse.julialang.org/t/most-elegant-way-to-fill-an-array-inside-for-loop/46914 "2020-09-19T13:59:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JohannesUl](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/johannesul/32/23685_2.png) [@JohannesUl](https://discourse.julialang.org/u/JohannesUl)\
**Post date:** [September 19, 2020, 1:59pm UTC](https://discourse.julialang.org/t/most-elegant-way-to-fill-an-array-inside-for-loop/46914/1 "2020-09-19T13:59:34Z")

</div>

Hi,

I am kind of new to the Julia language. I am looking for the most elegant way to fill an Array like in the following code section? (which does not work)

```
dr = Date(2020,9,12):Day(1):Date(2020,9,18)
openingHours = Array{Time,2}[]
for date in dr
    openingHours = [openingHours; Time(openingHoursYaml[gymName]["open"][Dates.dayname(date)]) Time(openingHoursYaml[gymName]["close"][Dates.dayname(date)])]
end

```

Since this is inside a function I don’t know in advance how many elements there will be inside dr. This way I cannot create the Array in advance but will need to build it in each iteration.

I hope I can get some good advice here to improove my code.

Best,  
Johannes

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [September 19, 2020, 2:06pm UTC](https://discourse.julialang.org/t/most-elegant-way-to-fill-an-array-inside-for-loop/46914/2 "2020-09-19T14:06:16Z")

</div>

I find your code a bit hard to read (an expression is possible redundant/repeated?), but you are perhaps looking for comprehensions:

[https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions](https://docs.julialang.org/en/v1/manual/arrays/#man-comprehensions)

---

<div class="post-metadata">

**Author:** ![JohannesUl](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/johannesul/32/23685_2.png) [@JohannesUl](https://discourse.julialang.org/u/JohannesUl)\
**Post date:** [September 19, 2020, 2:30pm UTC](https://discourse.julialang.org/t/most-elegant-way-to-fill-an-array-inside-for-loop/46914/3 "2020-09-19T14:30:15Z")

</div>

Thanks for this suggestion. The comprehension seems like the thing I have been looking for.
