# How to avoid multiple copies of a list when mapping a pure function to it?

Given this code:

mylist = Tuples[{a, e}, 2];
Insert[mylist, 1, {#, 3}] & /@ Range[2]

The output is this:

{{{a, a, 1}, {a, e}, {e, a}, {e, e}}, {{a, a}, {a, e, 1}, {e, a}, {e, e}}}

But the desired output is this:

{{a, a, 1}, {a, e,1}, {e, a}, {e, e}}

Apparently mylist is multiplied along the way. How to avoid this?

• Try Insert[mylist, 1, {{1, 3}, {2, 3}}] to get your output, which you could also write as Insert[mylist, 1, {#, 3} & /@ Range[2]] if you want to use Range. – MarcoB Jul 28 '17 at 20:40
• @MarcoB I am trying to understand the principle, such that I can also apply it in more complicated situations with more data. Then your solution is not efficient... – GambitSquared Jul 28 '17 at 20:42
• Your command generates a list of lists, each one with a single substitution. You want a single list, with two substitutions instead. There is a fundamental disconnect there, I'm afraid. It might be helpful to look at the output of Inactive[Insert][mylist, 1, {#, 3}] & /@ Range[2], i.e. to see the effect of mapping before the insertion happens. – MarcoB Jul 28 '17 at 20:45
• Related: (30647), (145999) – Mr.Wizard Jul 29 '17 at 8:38
• Possible duplicate: (36950) – Mr.Wizard Jul 29 '17 at 8:52

mylist = Tuples[{a, e}, 2];

I think MapAt would be a good candidate here

MapAt[Append[#, 1] &, mylist, List /@ Range[2]]

{{a, a, 1}, {a, e, 1}, {e, a}, {e, e}}

If you want Insert:

Fold[Insert[#1, 1, {#2, -1}] &, mylist, Range@2];

Or