# Applying a function of one variable to the elements of a list: map apply

### 5.40.29 Applying a function of one variable to the elements of a list: map apply

The apply and map commands can both apply a function to a list of elements, but take arguments in different orders (that is required for compatibility reasons). The apply command also works on matrices (see Section 5.44.6) and the map command also works on polynomials in internal sparse format (see Section 5.27.3).

- apply takes two arguments:
  - f, a function.
  - L, a list.
- apply(f,L) returns a list whose elements are f(x) for the elements x of L.

Note that apply returns a list ([]) even if the second argument is not a list.

#### Example.

Input:

apply(x->sqrt(x),[16,9,4,1])

Output:

⎡ ⎣ | 4,3,2,1 | ⎤ ⎦

- map takes two arguments:
  - L, a list or a polynomial in internal format (see Section 5.27.2).
  - f, a function.
- map(L,f) returns a list whose elements are f(x) for the elements x of L.

subsubsection*Example.
Input:

map([16,9,4,1],x->sqrt(x))

Output:

⎡ ⎣ | 4,3,2,1 | ⎤ ⎦

#### Examples.

- Input:
  apply(x->x^2,[3,5,1])
  or:
  map([3,5,1],x->x^2)
  (or first define the function h(x)=x2:)
  Input:
  h(x):=x^2
  then:
  apply(h,[3,5,1])
  or:
  map([3,5,1],h)
  Output:

  ⎡ ⎣ | 9,25,1 | ⎤ ⎦

- Define the function g(x)=[x,x2,x3]:
  Input:
  g:=(x)->[x,x^2,x^3]
  then:
  apply(g,[3,5,1])
  or:
  map([3,5,1],g)
  Output:

  ⎡
  ⎢
  ⎢
  ⎣

  3 | 9 | 27
  5 | 25 | 125
  1 | 1 | 1

  ⎤
  ⎥
  ⎥
  ⎦

Warning!!!
First purge x if x is not symbolic.
Note that if L1, L2 and L3 are lists, then sizes([L1,L2,L3]) is equivalent to map(size,[L1,L2,L3]).