I have list of the form

{y[-1], y[0], w'[1], y'[0], w'''[-1], z''[-1]}

and I would like to gather the elements together based on their heads to have

{{y[-1], y[0], y'[0]}, {w'[1], w'''[-1]}, {z''[-1]}}

My attempt so far has been to use

GatherBy[{y[-1], y[0], w'[1], y'[0], w'''[-1], z''[-1]}, FreeQ[Head[#], y] &]

which yields

{{y[-1], y[0], y'[0]}, {w'[1], w'''[-1], z''[-1]}}

I feel likes it's almost there and all it needs is to apply a similar function again on the subparts of the list above looking instead for heads that contain w and then z. But isn't there a more direct way to do what I want as this might become very cumbersome and slow when there are more than just three variables to check for ?

Thanks in advance.


1 Answer 1


Always start by looking at the FullForm:

{y[-1], y[0], w'[1], y'[0], w'''[-1], z''[-1]} // FullForm
myHead[Derivative[_][h_][_]] := h
myHead[h_[___]] := h

GatherBy[{y[-1], y[0], w'[1], y'[0], w'''[-1], z''[-1]}, myHead]

enter image description here

You can of course add other definitions to myHead to declare certain parts of other expressions as the "head" for the purpose of this gathering.

  • $\begingroup$ That's wizardry. Thanks very much $\endgroup$
    – jrekier
    Feb 11, 2017 at 22:58
  • $\begingroup$ @jrekier thanks :D $\endgroup$
    – Mr.Wizard
    Feb 11, 2017 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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