3
$\begingroup$

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},...}
$\endgroup$
2
  • $\begingroup$ {{a, b, c}, {d, e, f}} // Total? p.s. [#1 + #2] & /@ is not a valid syntax. $\endgroup$
    – Kuba
    Aug 8, 2019 at 10:01
  • 1
    $\begingroup$ possible duplicate: 71988 $\endgroup$
    – Kuba
    Aug 8, 2019 at 10:24

3 Answers 3

8
$\begingroup$

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}}

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

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}}*)
$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – M.B.
    Aug 8, 2019 at 10:20
  • $\begingroup$ Ups, sorry now I got it! $\endgroup$ Aug 8, 2019 at 10:36
0
$\begingroup$

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}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.