1

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?

GambitSquared
  • 2,311
  • 15
  • 23
  • 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
  • Possible duplicate: (36950) – Mr.Wizard Jul 29 '17 at 08:52

1 Answers1

3
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

Insert[mylist, 1, Thread[{Range@2, 3}]]

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

The problem with succesive insertions (and so with your idea) is that already after the first insertion the original positions have changed.

eldo
  • 67,911
  • 5
  • 60
  • 168