Consider the following three evaluations involving Flatten:

Flatten[f[f[f[x, y], 1, 2], f[x, y]], Infinity, f]

f[x, y, 1, 2, x, y] (* as expected *)

Flatten[List[f[f[x, y], 1, 2], f[x, y]], Infinity, f]

{x, y, 1, 2, x, y} (* as expected *)

Flatten[List[List[f[x, y], 1, 2], f[x, y]], Infinity, f]

{{f[x, y], 1, 2}, x, y} (* expected {{x, y, 1, 2}, x, y} *)

I would like to know why my expectation was wrong.


Flatten does not flatten the heads you indicate using the third optional argument, inside other heads. This is true for both the head List and other heads. In particular, the following does not come as a surprise:


(*   {f[{{1,2}}],f[{{3,4}}]}  *)

Flattening starts at level 1, not level 0, which is why you got your first and second example working. In the last example, the List head "stops" Flatten from flattening f inside lists, but the second part, being on level 1, is flattened all right.

This design is surely intentional. If you need to flatten inside other heads, this can be easily achieved by using replacement rules. I recommend reading this thread, which contains answers describing this issue and possible solutions in more detail.

| improve this answer | |
  • 4
    $\begingroup$ Your answer makes sense. The Mathematica documentation on Flatten is very sparse. I could not anticipate this behavior from the documentation. $\endgroup$ – m_goldberg Dec 19 '12 at 1:04
  • $\begingroup$ @m_goldberg Was glad to help, and thanks for the accept. $\endgroup$ – Leonid Shifrin Dec 19 '12 at 2:06

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.