# Map function over two lists

How to map a function over two lists, first one and than the other?

For example, assuming I have two lists {a,b,c} and {d,e,f}:

[#1 + #2] & /@ {{a,b,c},{d,e,f}}


That maps the expression simultaneously, but I want a result looking like:

{{a+d},{a+e},{a+f},{b+d},{b+e},...}

• {{a, b, c}, {d, e, f}} // Total? p.s. [#1 + #2] & /@ is not a valid syntax.
– Kuba
Aug 8, 2019 at 10:01
• possible duplicate: 71988
– Kuba
Aug 8, 2019 at 10:24

You can use Outer or Tuples as follows:

Join @@ Outer[List @* Plus, {a, b, c}, {d, e, f}]


{{a + d}, {a + e}, {a + f}, {b + d}, {b + e}, {b + f}, {c + d}, {c + e}, {c + f}}

Map[List @* Total] @ Tuples[ {{a, b, c}, {d, e, f}}]


{{a + d}, {a + e}, {a + f}, {b + d}, {b + e}, {b + f}, {c + d}, {c + e}, {c + f}}

Also

List /@ Total /@ Tuples[ {{a, b, c}, {d, e, f}}] (* or *)
Tuples[foo[{a, b, c}, {d, e, f}]] /. foo -> List @* Plus


{{a + d}, {a + e}, {a + f}, {b + d}, {b + e}, {b + f}, {c + d}, {c + e}, {c + f}}

• Also can be written as {{a, b, c}, {d, e, f}} // Tuples // Map[Total /* List] Aug 8, 2019 at 13:13

Try using Distribute:

Distribute[{{a, b, c}, {d, e, f}}, List]
(*{{a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c,f}}*)

• I actually want to get {{a+d},{a+e},{a+f},{b+d},{b+e},...}, not {a + d, b + e, c + f} . So that the {a, b, c} list is mapped first, and then the other one.
– M.B.
Aug 8, 2019 at 10:20
• Ups, sorry now I got it! Aug 8, 2019 at 10:36

As with other solutions, you have to do some cleaning up afterword, but you can use Table with lists defining the iterators:

Flatten[Table[{i + j}, {i, {a, b, c}}, {j, {d, e, f}}], 1]


If you really want to map it onto the lists, you can use the following, but the result is the same:

Flatten[Table[{i + j}, {i, #1}, {j, #2}], 1] & @@ {{a, b, c}, {d, e, f}}


either option outputs:

{{a + d}, {a + e}, {a + f}, {b + d}, {b + e}, {b + f}, {c + d}, {c + e}, {c + f}}