2
$\begingroup$

I apologise for the simple question, but I've trying to learn to write my code in a more idiomatic way, after having learned Mathematica mostly through trial and error for a long time.

Say I have two lists

l1={x,y,z}
l2={a,b,c}

And I want to create a replacement rule

{x->a,y->b,z->c}

I can achieve this through

Table[l1[[i]] -> l2[[i]], {i, 1, Length[l1]}]

But this feels cumbersome and I was wondering if there's a cleaner, more idiomatic way of making the same replacement rule?

$\endgroup$
  • 1
    $\begingroup$ Take a look at Thread / AssociationThread. $\endgroup$ – Kuba Jun 5 at 19:30
4
$\begingroup$
Thread[ l1 -> l2]

Should do the trick.

$\endgroup$
1
$\begingroup$

As usual, in Mathematica, there are several ways to do it.

Rule@@@Transpose@{l1, l2}

is one way although

Thread@Rule[l1, l2]

is probably more direct.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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