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?

  • $\begingroup$ 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. $\endgroup$ – MarcoB Jul 28 '17 at 20:40
  • $\begingroup$ @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... $\endgroup$ – GambitSquared Jul 28 '17 at 20:42
  • $\begingroup$ 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. $\endgroup$ – MarcoB Jul 28 '17 at 20:45
  • $\begingroup$ Related: (30647), (145999) $\endgroup$ – Mr.Wizard Jul 29 '17 at 8:38
  • $\begingroup$ Possible duplicate: (36950) $\endgroup$ – 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];


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.


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.