# Altering the Values of Global Lists Within Tables

Say I have some lists:

list1 = {4}
list2 = {2}
list3 = {6}
list4 = {9}
list5 = {7}.


I want to alter them in a table like so:

Table[Append[ToExpression["list" <> ToString[n]], n], {n, 1, 5}].


This produces the desired results.

{{4, 1}, {2, 2}, {6, 3}, {9, 4}, {7, 5}}


However, the lists remain unchanged in the global environment.

list1
list2
list3
list4
list5

{4}
{2}
{6}
{9}
{7}


How do I build lists up within Tables in this way so that their global values change?

I believe it requires the use of AppendTo as opposed to Append but merely changing it in the code above renders errors.

The following code using the Piecewise function in conjunction with AppendTo works but it requires explicitly writing out each case and the point is to avoid this.

Table[Piecewise[{{AppendTo[list1, n], n == 1}, {AppendTo[list2, n],
n == 2}, {AppendTo[list3, n], n == 3}, {AppendTo[list4, n],
n == 4}, {AppendTo[list5, n], n == 5}}], {n, 1, 5}]

• TIP: never use ToExpression. In this case, it's better to define the lists as list[1] = {...}; list[2] = {...}; etc. Jun 3, 2018 at 2:10
• Probably you should read the answers to this question. Jun 3, 2018 at 10:06

Table[ToExpression["AppendTo[list"<>ToString[n]<>","<>ToString[n]<>"]"], {n,1,5}];

will do that without errors and resulting in list1 having the value {4,1}, list5 having the value {7,5} etc.