0
$\begingroup$

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}]
$\endgroup$
2
  • 3
    $\begingroup$ TIP: never use ToExpression. In this case, it's better to define the lists as list[1] = {...}; list[2] = {...}; etc. $\endgroup$ Commented Jun 3, 2018 at 2:10
  • $\begingroup$ Probably you should read the answers to this question. $\endgroup$
    – rhermans
    Commented Jun 3, 2018 at 10:06

1 Answer 1

1
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.