Say I have two lists,

list1 = {{a, b}, {c, d}}
list2 = {{x, y, z},{x1, y1, z1}}

and I want to map a function f over them to produce

{{f[x, {a, b}], f[y, {a,b}], f[z, {a,b}]},{f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}

I tried some Mappings, but it seems really complex thing.
Is it possible to generate? Thank you.

  • $\begingroup$ related topics: 96803, 38023 $\endgroup$ – Kuba May 2 '17 at 14:48

Modified answer from a closely related topic:

How to use Map inside MapThread?

MapThread[Function[{u, b}, f[#, b] & /@ u], {list2, list1}]
 {f[x, {a, b}], f[y, {a, b}], f[z, {a, b}]}, 
 {f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}

This is on of those cases where an ordinary Table loop is by far the easiest solution:


Alternatively, you can use MapIndexed

  • $\begingroup$ It's all about the speed, as my real lists are really big. Thank you. $\endgroup$ – Davit Shahnazaryan May 2 '17 at 14:54
Map[Function[arg, f[arg, #1}]], #2] & @@@ Transpose[{list1, list2}]

or, more similar to Kuba's answer

MapThread[Map[Function[arg, f[arg, #1]], #2] &, {list1, list2}]

both yielding

{{f[x, {a, b}], f[y, {a, b}], f[z, {a, b}]},
 {f[x1, {c, d}], f[y1, {c, d}], f[z1, {c, d}]}}

Ok, it's solved with Distribute.

Distribute[f[{#1}, #2], 
   List] & @@@ {{list2[[1]], list1[[1]]}, {list2[[2]], list1[[2]]}}

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.