# Returning a function multiple time to an array

**URL:** <https://discourse.julialang.org/t/returning-a-function-multiple-time-to-an-array/55541>\
**Category:** General Usage\
**Created:** [February 18, 2021, 1:35pm UTC](https://discourse.julialang.org/t/returning-a-function-multiple-time-to-an-array/55541 "2021-02-18T13:35:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marouane](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marouane/32/16267_2.png) [@marouane](https://discourse.julialang.org/u/marouane)\
**Post date:** [February 18, 2021, 1:35pm UTC](https://discourse.julialang.org/t/returning-a-function-multiple-time-to-an-array/55541/1 "2021-02-18T13:35:16Z")

</div>

i have this function that i’m trying to call it more than once and push the return value to an array

```julia
function f(x,y)
    
    return s=x+y
end
for i=0:3
    x=i*pi/2
    s=f(x,2)
    global X=[]
    push!(X,s)
end
X

```

but all i get is the last value which means for `i=3` but i want all the values to be appended in the array `X`

---

<div class="post-metadata">

**Author:** ![nilshg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nilshg/32/2283_2.png) [@nilshg](https://discourse.julialang.org/u/nilshg)\
**Post date:** [February 18, 2021, 1:46pm UTC](https://discourse.julialang.org/t/returning-a-function-multiple-time-to-an-array/55541/2 "2021-02-18T13:46:22Z")

</div>

You are creating a new `X` in every loop iteration, so what you see is only the `X` created for `i=3`, which has only one value in it. You want to create `X` once outside the loop:

```julia
julia> X = [];

julia> for i=0:3
           x=i*pi/2
           s=f(x,2)
           push!(X,s)
       end

julia> X
4-element Vector{Any}:
 2.0
 3.5707963267948966
 5.141592653589793
 6.71238898038469

```

As an aside, don’t use `[]` to create arrays - as you see above this creates a `Vector{Any}`, which is terrible for performance. In this case, you should use `X = Float64[]` to instantiate your array.

As a further aside, it is often helpful to allocate memory in advance rather than `push!`ing in a loop if you know the size of your result, i.e. `X = Vector{Float64}(undef, 4)` or `X = zeros(4)`.
