I use Last to extract the last element of an expression. Let poly=a+b*c+Log[a]+z.


When Using Last@poly, I expect the output is z. However, the command gave me Log[a].


With FullForm@poly, I found the output is Plus[a,Times[b,c],z,Log[a]]. So, Log[a] should be the correct answer of the command, but not my expected answer.

My Question

The strange behavior confuse me.

  1. I wonder whether elements of an expression in mathematica have definite order.
  2. If the answer is "no", is there any alternative other than Last to avoid the undetermined behavior, so that I can extract particular element ?

1 Answer 1


I wonder whether elements of an expression in mathematica have definite order.

Yes, the one you get after evaluating an expression. See Polynomial Ordering in the Wolfram Documentation Center. In your case, poly = a + b*c + Log[a] + z evaluates to

a + b c + z + Log[a]

So Last does indeed do what it's supposed to.

You could try extracting the elements with patterns (depending on what terms you actually need to extract), or you could use something like PolynomialForm[%,TraditionalOrder->True] (found here).

Some general information about term ordering in Mathematica

Functions in Mathematica can have the Orderless attribute, which means that Mathematica will (re)arrange the supplied terms in canonical order, as described in this tutorial. Canonical ordering is used as a standard way to arrange terms in commutative and associative functions (such as Plus or Times in your case) for purposes of for example pattern matching.

  • 2
    $\begingroup$ Can you please also mention Orderless and link to the relevant tutorial? $\endgroup$
    – Szabolcs
    Nov 7, 2015 at 10:04
  • $\begingroup$ I added the information, thanks. $\endgroup$
    – Graumagier
    Nov 7, 2015 at 10:18

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.