# Using Map multiple times in one command

Is there a way to reproduce the effect of

Table[i ** j, {i, list1}, {j, list2}]


using Map instead of Table? Specifically, I want to write something along the lines of

#2 ** #1 & /@ list2 & /@ list1


but tell Mathematica that the first Map (/@ list2) should map list2 into #1 and the second Map (/@ list1) should map list1 into #2. In other words, I basically want Mathematica to evaluate the first Map (/@ list2) like this:

temp = {# ** list2[[1]], ..., # ** list2[[-1]]}&


and then evaluate the second Map (/@ list1) and return

temp /@ list1


which should be equivalent to the Table command above.

• Outer[NonCommutativeMultiply, list1, list2]. Outer is the best. Sep 8 '15 at 4:24
• I believe @march's is the right one. Just in case you could also get something similar with f @@@ Tuples[{list1, list2}] Sep 8 '15 at 4:38

If you insist on using Map, then you can nest it using its explicit form, as

Map[Function[t, Map[t ** # &, list2]], list1]


where you have to use an explicit Function call to avoid the confusion you note.

... but as mentioned by march in the comments, the natural way is to use Outer, as

Outer[NonCommutativeMultiply, list1, list2]


Another clean alternative is to use Tuples and @@@, as

NonCommutativeMultiply @@@ Tuples[{list1, list2}]


as pointed out by belisarius, which will yield a flat list.

• I think you have list1 and list2 in the wrong spots. I think you meant Map[Function[t, Map[t ** # &, list2]], list1] Sep 8 '15 at 12:16
• @Jack Good catch, thanks. Sep 8 '15 at 12:56
• Thanks! The explicit function call with specified argument was what I needed. I need to use Map instead of Outer or Tuples because I actually need to do further, more complicated manipulations within the inner Map than just a direct product type operation. I should have known better than to try to simplify my problem in my post instead of presenting exactly what I needed! Sep 8 '15 at 17:04
• @tparker There is another one : Distribute[NonCommutativeMultiply[list1, list2], List] Sep 8 '15 at 23:15
• @tparker If you want to do some "more complicated things within the inner Map", I understand you want to apply some function to list2 elements ? In that case you can use these forms : Outer[f[#1, g[#2]] &, list1, list2] or f[#1, g[#2]] & @@@ Tuples[{list1, list2}] or Distribute[f[list1, g /@ list2], List]. Try these general examples replacing f by NonCommutativeMultiply and let set list1 = {x, y, z}; list2 = {a, b};. Is that what you meant ? Sep 8 '15 at 23:22