Wolfram: Map Function to List
Map (apply to each Element)
Map[f, list]
-
🔸 SHORT SYNTAX:
f /@ list
Apply a function to each element, return the result list.
(* Map a function to list *) Map[ f, {3,4,5} ] (* {f[3], f[4], f[5]} *) (* short syntax *) f /@ {3,4,5}
(* Map a user-defined function to list *) Map[ Function[x, x+1 ], {1, 2, 3} ] (* {2, 3, 4} *)
Map a Function to Tree Nodes
Map[f, list, levelSpec]
-
Apply a function to each element, at Level Spec .
💡 TIP: one great use is map to leafs of a tree by using
{-1}
for levelSpec.(* map to 1st level *) Map[ f, {1, {2, {3}}}, {1} ] (* {f[1], f[{2, {3}}]} *) (* map to 2nd level *) Map[ f, {1, {2, {3}}}, {2} ] (* {1, {f[2], f[{3}]}} *) (* map to 3rd level *) Map[ f, {1, {2, {3}}}, {3} ] (* {1, {2, {f[3]}}} *) (* map to leafs *) Map[ f, {1, {2, {3}}}, {-1} ] (* {f[1], {f[2], {f[3]}}} *)
Map with Index
MapIndexed
-
MapIndexed[ f, list ]
MapIndexed[ f, list, levelSpec ]
→ map at Level Spec
Like
Map
, but also feed the index to the function.💡 TIP: Useful when you want to go over a list but also need the index.
The function receive 2 args, first is value, second is the Position spec of the value.
MapIndexed[ f, {a,b,c} ] (* {f[a, {1}], f[b, {2}], f[c, {3}]} *) (* map at level 2 *) MapIndexed[ f, {{a}, {b}}, {2} ] (* {{f[a, {1, 1}]}, {f[b, {2, 1}]}} *) (* map at level -1 *) MapIndexed[ f, {{a}, {b}, c}, {-1} ] (* {{f[a, {1, 1}]}, {f[b, {2, 1}]}, f[c, {3}]} *)
Map for function with multiple parameters
MapThread
-
MapThread[ f, {list1 , list2, etc} ]
MapThread[ f, {list1 , list2, etc}, n ]
→ map at Level n
Like
Map
, but for functions that take 2 args (or more). The function is given args from each list.MapThread[ f, {{1, 2, 3} , {a, b, c}} ] (* {f[1, a], f[2, b], f[3, c]} *) MapThread[f, {{1, 2, 3}, {a, b, c}, {x, y, z}}] (* {f[1, a, x], f[2, b, y], f[3, c, z]} *)
(* map to level 2 *) MapThread[ f, {{{1}, {2}} , {{a}, {b}}} , 2 ] (* {{f[1, a]}, {f[2, b]}} *)