Applying Functions to Lists and Other Expressions

In an expression like you are giving a list as the argument to a function. Often you need instead to apply a function directly to the elements of a list, rather than to the list as a whole. You can do this in Mathematica using Apply.

This makes each element of the list an argument of the function .
In[1]:=
Click for copyable input
Out[1]=
This gives Times[a, b, c] which yields the product of the elements in the list.
In[2]:=
Click for copyable input
Out[2]=
Here is a definition of a function that works like the built-in function GeometricMean, written using Apply.
In[3]:=
Click for copyable input
Apply[f,{a,b,...}]apply f to a list, giving
Apply[f,expr] or f@@exprapply f to the top level of an expression
Apply[f,expr,{1}] or f@@@exprapply f at the first level in an expression
Apply[f,expr,lev]apply f at the specified levels in an expression

Applying functions to lists and other expressions.

What Apply does in general is to replace the head of an expression with the function you specify. Here it replaces Plus by List.
In[4]:=
Click for copyable input
Out[4]=
Here is a matrix.
In[5]:=
Click for copyable input
Out[5]=
Using Apply without an explicit level specification replaces the top-level list with .
In[6]:=
Click for copyable input
Out[6]=
This applies only to parts of at level 1.
In[7]:=
Click for copyable input
Out[7]=
This applies at levels 0 through 1.
In[8]:=
Click for copyable input
Out[8]=
New to Mathematica? Find your learning path »
Have a question? Ask support »