How to | Map a Function over a List

Mathematica includes many powerful operations for working with lists. It is often desirable to map a function onto each individual element in a list. While listable functions do this by default, you can use Map to do this with non-listable functions.

First set up a list of the integers from 1 to 5:

In[293]:=
Click for copyable input
Out[293]=

You can map a function over every element of the list using Map; this example uses an undefined function :

In[294]:=
Click for copyable input
Out[294]=

You can use as a shorthand for Map (this is the same command as in the previous example):

In[295]:=
Click for copyable input
Out[295]=

Most mathematical functions have the Listable property, meaning they automatically map over lists:

In[296]:=
Click for copyable input
Out[296]=
In[297]:=
Click for copyable input
Out[297]=

If the function is not Listable, you can use Map, instead. Set up a list of five 2×2 matrices:

In[298]:=
Click for copyable input
Out[298]=

Use Map to map MatrixForm over the list to see each of them in mathematical notation:

In[299]:=
Click for copyable input
Out[299]=

Now use Map to calculate the eigenvalues of each of the matrices in the list:

In[300]:=
Click for copyable input
Out[300]=

Map does not just operate on lists. It can be used for any expression:

In[301]:=
Click for copyable input
Out[301]=
    

Apply is another functional programming operation. It replaces the head of an expression.

You can see how this works using two undefined functions, and :

In[302]:=
Click for copyable input
Out[302]=

Apply has for a shorthand notation (this is the same command as the previous example):

In[303]:=
Click for copyable input
Out[303]=

Common expressions are shown in StandardForm in Mathematica, but their underlying FullForm shows how Apply can be used:

In[304]:=
Click for copyable input
Out[304]=

For example, this changes a sum into a product:

In[305]:=
Click for copyable input
Out[305]=
    

Apply is useful when you want to turn the elements in a list into function arguments.

Create a list of five ordered pairs :

In[306]:=
Click for copyable input
Out[306]=

Mod finds the remainder when dividing the first number of an ordered pair by the second:

In[307]:=
Click for copyable input
Out[307]=

To apply Mod to all of the pairs, you need to work at level 1 of the list (specified by the ):

In[308]:=
Click for copyable input
Out[308]=

You can use as a shorthand to apply at level 1:

In[309]:=
Click for copyable input
Out[309]=

This is another way to do the same thing using a pure function with Function:

In[310]:=
Click for copyable input
Out[310]=

This uses the short form of Function:

In[311]:=
Click for copyable input
Out[311]=
New to Mathematica? Find your learning path »
Have a question? Ask support »