Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

MapIndex returns the index in a list instead of as shown in my revised example. I can work with it (or work around it), but what's the design concept? It seems like an unnecessary complication, but I'm sure there is a reason I don't see.

enter image description here

I tagged this with a design-pattern tag. I'm not sure if that's appropriate. Editors please remove the tag if it's not.

share|improve this question
I guess this is due to the fact that once you provide a levelspec, it becomes necessary, consider: MapIndexed[f, {{a, b}, {c, d, e}}, {2}] – Pinguin Dirk Sep 17 '13 at 18:30
In addition to what others said, one can remove this {} using First@ like this: MapIndexed[f[#1, First@#2] &, {a, b, c, d}] gives {f[a, 1], f[b, 2], f[c, 3], f[d, 4]} – Nasser Sep 17 '13 at 18:33
@PinguinDirk I just looked at your example and see how it works. Level specifications are tricky: e.g. 2 vs {2}. I know how it works, but I try to stay on deck one. – George Wolfe Sep 17 '13 at 18:44
Today's interest in expression diffs reminded me about my expression diff code, where there is an application of MapIndexed mapping on possibly deeply nested expression - there I used the second argument essentially as a unique Id for a part in an expression. – Leonid Shifrin Sep 18 '13 at 10:38
up vote 12 down vote accepted

The "unnecessary" complication is needed for those cases where you specify deeper levels than the first:

MapIndexed[f, {{a}, {b}}, {2}]
(* {{f[a, {1, 1}]}, {f[b, {2, 1}]}} *)

The following code produces what you want:

myMapIndexed[f_, l_] := Inner[f, l, Range[Length[l]], List];
myMapIndexed[f, {a, b, c, d}]
(* {f[a, 1], f[b, 2], f[c, 3], f[d, 4]} *)
share|improve this answer
I get it. I haven't had an application with a nested structure come up in anything I've done. Thanks. – George Wolfe Sep 17 '13 at 18:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.