Special Forms of Assignment

Particularly when you write procedural programs in the Wolfram Language, you will often need to modify the value of a particular variable repeatedly. You can always do this by constructing the new value and explicitly performing an assignment such as x=value. The Wolfram Language, however, provides special notations for incrementing the values of variables, and for some other common cases.

 i++ increment the value of i by 1 i-- decrement i ++i pre‐increment i --i pre‐decrement i i+=di add di to the value of i i-=di subtract di from i x*=c multiply x by c x/=c divide x by c

Modifying values of variables.

This assigns the value 7x to the variable t.
 In[1]:=
 Out[1]=
This increments the value of t by 18x.
 In[2]:=
 Out[2]=
The value of t has been modified.
 In[3]:=
 Out[3]=
This sets t to 8, multiplies its value by 7, then gives the final value of t.
 In[4]:=
 Out[4]=
The value of i++ is the value of i before the increment is done.
 In[5]:=
The value of ++i is the value of i after the increment.
 In[6]:=
 x=y=value assign the same value to both x and y {x,y}={value1,value2} assign different values to x and y {x,y}={y,x} interchange the values of x and y

Assigning values to several variables at a time.

This assigns the value 5 to x and 8 to y.
 In[7]:=
 Out[7]=
This interchanges the values of x and y.
 In[8]:=
 Out[8]=
Now x has value 8.
 In[9]:=
 Out[9]=
And y has value 5.
 In[10]:=
 Out[10]=
You can use assignments to lists to permute values of variables in any way.
 In[11]:=
 Out[11]=

When you write programs in the Wolfram Language, you will sometimes find it convenient to take a list, and successively add elements to it. You can do this using the functions PrependTo and AppendTo.

 PrependTo[v,elem] prepend elem to the value of v AppendTo[v,elem] append elem v={v,elem} make a nested list containing elem

Assignments for modifying lists.

This assigns the value of v to be the list {5,7,9}.
 In[12]:=
 Out[12]=
This appends the element 11 to the value of v.
 In[13]:=
 Out[13]=
Now the value of v has been modified.
 In[14]:=
 Out[14]=

Although AppendTo[v,elem] is always equivalent to v=Append[v,elem], it is often a convenient notation. However, you should realize that because of the way the Wolfram System stores lists, it is usually less efficient to add a sequence of elements to a particular list than to create a nested structure that consists, for example, of lists of length 2 at each level. When you have built up such a structure, you can always reduce it to a single list using Flatten.

This sets up a nested list structure for w.
 In[15]:=
 Out[15]=
You can use Flatten to unravel the structure.
 In[16]:=
 Out[16]=