This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
 Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Transformation Rules and Definitions  /

2.4.4 Special Forms of Assignment

Particularly when you write procedural programs in Mathematica, 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. Mathematica, however, provides special notations for incrementing the values of variables, and for some other common cases.

Modifying values of variables.

  • This assigns the value 7x to the variable t.
  • In[1]:= t = 7x


  • This increments the value of t by 18x.
  • In[2]:= t += 18x


  • The value of t has been modified.
  • In[3]:= t


  • This sets t to 8, multiplies its value by 7, then gives the final value of t.
  • In[4]:= t = 8; t *= 7; t


  • The value of i++ is the value of ibefore the increment is done.
  • In[5]:= i=5; Print[i++]; Print[i]



  • The value of ++i is the value of iafter the increment.
  • In[6]:= i=5; Print[++i]; Print[i]



    Assigning values to several variables at a time.

  • This assigns the value 5 to x and 8 to y.
  • In[7]:= {x, y} = {5, 8}


  • This interchanges the values of xy.
  • In[8]:= {x, y} = {y, x}


  • Now x has value 8.
  • In[9]:= x


  • And y has value 5.
  • In[10]:= y


  • You can use assignments to lists to permute values of variables in any way.
  • In[11]:= {a, b, c} = {1, 2, 3}; {b, a, c} = {a, c, b}; {a, b, c}


    When you write programs in Mathematica, 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.

    Assignments for modifying lists.

  • This assigns the value of v to be the list {5,7,9}.
  • In[12]:= v = {5, 7, 9}


  • This appends the element 11 to the value of v.
  • In[13]:= AppendTo[v, 11]


  • Now the value of v has been modified.
  • In[14]:= v


    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 Mathematica 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]:= w = {1}; Do[ w = {w, k^2}, {k, 1, 4} ]; w


  • You can use Flatten to unravel the structure.
  • In[16]:= Flatten[w]