# How to change the name of a variable in a for loop

**URL:** https://discourse.julialang.org/t/how-to-change-the-name-of-a-variable-in-a-for-loop/28510
**Category:** New to Julia
**Created:** [September 7, 2019, 7:32pm UTC](https://discourse.julialang.org/t/how-to-change-the-name-of-a-variable-in-a-for-loop/28510 "2019-09-07T19:32:36Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![trean024](https://avatars.discourse-cdn.com/v4/letter/t/90db22/32.png) [@trean024](https://discourse.julialang.org/u/trean024)
#### Post date: [September 7, 2019, 7:32pm UTC](https://discourse.julialang.org/t/how-to-change-the-name-of-a-variable-in-a-for-loop/28510/1 "2019-09-07T19:32:36Z")

</div>

I would like to change the name of a variable within a for loop, using the loop index in the name of the variable.

I’ve tried the following syntax:

```julia
A= [1,2,3]
nargs = length(A)
for i = 1:nargs
    global x{i}
    x{i}=A[i]
end

```

This isn’t the right syntax, and googling has not led me to the correct syntax.

I’ve also tried

```julia
A= [1,2,3]
nargs = length(A)
for i = 1:nargs
    global x$i
    x$i=A[i]
end

```

My hope is to create three variables, x1, x2, and x3 each containing the appropriate element of A. I will not know the size of A beforehand, which is why I thought to do it this way.

---

<div class="post-metadata">

### Author: ![simeonschaub](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simeonschaub/32/216566_2.png) [@simeonschaub](https://discourse.julialang.org/u/simeonschaub)
#### Post date: [September 7, 2019, 7:43pm UTC](https://discourse.julialang.org/t/how-to-change-the-name-of-a-variable-in-a-for-loop/28510/2 "2019-09-07T19:43:16Z")

</div>

This works:

```julia
for i = 1:nargs
    @eval $(Symbol(:x, i)) = A[$i]
end

```

But you will pretty much always be better off using a vector or tuple instead, so I really wouldn’t recommend using this in non-toy code. You also don’t need `global` here, since `eval` always works in global scope.

---

<div class="post-metadata">

### Author: ![trean024](https://avatars.discourse-cdn.com/v4/letter/t/90db22/32.png) [@trean024](https://discourse.julialang.org/u/trean024)
#### Post date: [September 7, 2019, 7:53pm UTC](https://discourse.julialang.org/t/how-to-change-the-name-of-a-variable-in-a-for-loop/28510/3 "2019-09-07T19:53:31Z")

</div>

Thank you!
