WolframLang: Map Function to List

By Xah Lee. Date: . Last updated: .
Map[f, expr]
(Short syntax: f /@ expr)
Like many language's map, but can map to specific level of a nested list, such as at leafs of a tree. e.g. Map[ f, {1, {{2}, 3}}, {-1} ] === {f[1], {{f[2]}, f[3]}} Map
Scan[f, expr]
Same as Map, but return Null. use this if you no need return value. Scan

Map a builtin function to list:

ii = {1, {2, 3}};

Map[ Length, ii ]
(* {0, 2} *)

(* short syntax *)
Length /@ ii
(* {0, 2} *)

Map a user function to list:

ii = {1, {2, 3}};

Map[ Function[{x}, x^2 ], ii ]
(* {1, {4, 9}} *)

(* short syntax *)
(#^2 &) /@ ii
(* {1, {4, 9}} *)

Map a function to different levels of a rectangular array:

x = Table[{i, j}, {i, 2}, {j, 2}]
(* {{{1, 1}, {1, 2}}, {{2, 1}, {2, 2}}} *)

(* map to 1st level, as in flat map *)
Map[ f, x, {1} ]
(* {f[{{1, 1}, {1, 2}}], f[{{2, 1}, {2, 2}}]} *)

(* map to 2nd level *)
Map[ f, x, {2} ]
(* {{f[{1, 1}], f[{1, 2}]}, {f[{2, 1}], f[{2, 2}]}} *)

(* map to 3rd level *)
Map[ f, x, {3} ]
(* {{{f[1], f[1]}, {f[1], f[2]}}, {{f[2], f[1]}, {f[2], f[2]}}} *)

(* map to deepest level, the leafs. in this case, same as 3rd level *)
Map[ f, x, {-1} ]
(* {{{f[1], f[1]}, {f[1], f[2]}}, {{f[2], f[1]}, {f[2], f[2]}}} *)
WolframLang level of nesting 2021-11-23
WolframLang map to different levels of nesting

Map to a tree.

tree = {a, {{b,c}, d}, e};

(* map to top level *)
Map[ f, tree ]
(* {f[a], f[{{b, c}, d}], f[e]} *)

(* same as 1st level *)
Map[ f, tree, {1} ]
(* {f[a], f[{{b, c}, d}], f[e]} *)

(* map to leafs *)
Map[ f, tree, {-1} ]
(* {f[a], {{f[b], f[c]}, f[d]}, f[e]} *)
MapIndexed
Like Map, but also feed the index info to the function. Useful when you want to “iterate” over array but need the index, not just value. The function receive 2 args, first is value, second is the position of the value. The position is in standard form {i, j, ...}, a list of indexes that specify the item position.
MapIndexed[ f, {a,b,c} ]
(* {f[a, {1}], f[b, {2}], f[c, {3}]} *)
MapIndexed
MapThread
Like Map, but for functions that take more than 1 arg.
x = {{1, 2, 3} , {a, b, c} };
MapThread[ f, x ]
(* {f[1, a], f[2, b], f[3, c]} *)
li = {{1, 2, 3}, {a, b, c}, {x, y, z} };
MapThread[f, li]
(* {f[1, a, {{1, 2, 3}, {a, b, c}}], f[2, b, y], f[3, c, z]} *)
MapThread

WolframLang Loop, Iteration, Recursion

List

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc