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

This question already has an answer here:

Why does

Flatten[f[g[a, f[b]], f[c, d]]]

result in

f[g[a, f[b]], c, d]

I expected the answer to be

f[g[a, b], c, d]

What is wrong in this code?

share|improve this question

marked as duplicate by Mr.Wizard Jun 27 '15 at 9:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

See the third entry under the details for Flatten in the documentation: Since the head is f, only those subexpressions of it that are also f get flattened. – ciao Jun 16 '14 at 7:13
Related question here – m_goldberg Jun 16 '14 at 7:29
Thank you! I think i know what the reason is.the hyperlink let me enlightened. – partida Jun 16 '14 at 7:56
up vote 8 down vote accepted


Flatten[f[g[a, f[b]], f[c, d]]]

(* f[g[a, f[b]], c, d] *)

Flatten[k[g[a, f[b]], f[c, d]]]

(* k[g[a, f[b]], f[c, d]] *)

Note the second does... nothing. That's because Flatten looks at the head of the expression (f and k respectively above), and only flattens subexpressions within with the same head.

You can see this described in the details section, etc. for the Flatten function.

share|improve this answer
+1 as you actually answer the question and provide illustration...congratulations on >10K btw – ubpdqn Jun 16 '14 at 7:23
Suddenly understand ,I misunderstand the meaning in the document – partida Jun 16 '14 at 8:00

This does not answer your question about Flatten. However, rasher's comment does. Here are some approaches to achieve your goal:

f[f[g[a, f[b]], f[c, d]] /. f -> Sequence]


# /. f -> Sequence & /@ f[g[a, f[b]], f[c, d]]
share|improve this answer
Bases covered! +1 – ciao Jun 16 '14 at 7:41
Excellent! This is what I want,thank you! – partida Jun 16 '14 at 7:57

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