0

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}]
David Caliri
  • 287
  • 1
  • 6

1 Answers1

1

If you really want to do that the way you say you want to do that then

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.

Bill
  • 12,001
  • 12
  • 13