Wolfram Research

Function Repository Resource:

SwapSymbolValues

Source Notebook

Swap values of symbols using a temporary variable

Contributed by: Taliesin Beynon (Wolfram Research)

ResourceFunction["SwapSymbolValues"][x,y]

swaps the values of symbols x and y.

Details and Options

ResourceFunction["SwapSymbolValues"] uses a temporary symbol to swap values of its arguments.
ResourceFunction["SwapSymbolValues"][x,y] is equivalent to Block[{t = x}, x = y; y = t].
The return value of ResourceFunction["SwapSymbolValues"][x,y] is y.
SwapSymbolValues has attribute HoldAll.

Examples

Basic Examples

Swap values:

In[1]:=
a = 1; b = 2;
In[2]:=
ResourceFunction["SwapSymbolValues"][a, b]
Out[2]=
In[3]:=
{a, b}
Out[3]=

Possible Issues

You cannot reassign raw objects:

In[4]:=
ResourceFunction["SwapSymbolValues"]["x", "y"]
Out[4]=

Use symbols to swap their values:

In[5]:=
x = "x"; y = "y";
In[6]:=
ResourceFunction["SwapSymbolValues"][x, y]
Out[6]=
In[7]:=
{x, y}
Out[7]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information