5
$\begingroup$

I am struggling to find a way to assign a value from a list to names from another pre-defined list with Table[].

names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}

What I want is:

first = {1, 1}
second = {2, 2}
third = {3, 3}

so that {1, 1} is stored in first etc.

I tried the following:

namelists = Table[(names[[i]]) = (numbers[[i]]), {i, Length[names]}];

In this case, namelists[[1]] = {1, 1}, however first does not store any information...

$\endgroup$
1
  • 2
    $\begingroup$ If you are not set on using Table then MapThread[Set, {names, numbers}] $\endgroup$
    – Edmund
    Dec 23, 2019 at 12:44

4 Answers 4

11
$\begingroup$
Clear[first, second, third]
names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}
Table[Evaluate[names[[i]]] = numbers[[i]], {i, 3}]
first
second
third
$\endgroup$
1
  • 4
    $\begingroup$ Since you can make multiple assignments at the same time, you don't need the Table: the "vectorized" Evaluate@names = numbers will work too. $\endgroup$
    – MarcoB
    Dec 23, 2019 at 15:50
9
$\begingroup$
Clear[first, second, third]    

names = {first, second, third};
numbers = {{1, 1}, {2, 2}, {3, 3}};

With[{names = names}, names = numbers];

first

{1, 1}

$\endgroup$
8
$\begingroup$

With the following definitions:

Clear[first, second, third]
names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}

a one-liner approach would be:

Evaluate@names = numbers

You can see how this works using Trace:

Clear[first, second, third]
names = {first, second, third}
numbers = {{1, 1}, {2, 2}, {3, 3}}
Trace[Evaluate@names = numbers]

(* Out: 
{{names, {first, second, third}}, 
   {numbers, {{1, 1}, {2, 2}, {3, 3}}}, 
   {first, second, third} = {{1, 1}, {2, 2}, {3, 3}}, 
   {{1, 1}, {2, 2}, {3, 3}}} *)
$\endgroup$
6
$\begingroup$

MapThread works well for this task.

numbers = {{1, 1}, {2, 2}, {3, 3}};
Clear[first, second, third]
names = {first, second, third};
MapThread[Set, {names, numbers}]; 
{first, second, third}

{{1, 1}, {2, 2}, {3, 3}}

$\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.