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

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.

share|improve this question
up vote 14 down vote accepted

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.

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

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.