3
$\begingroup$

Suppose I have a list of the form

list={a+b,c+d,Xi+Psi*Zeta,0}

How can I make a list of only the first term of each element in that list? In this case the list would be just

list2={a,c,Xi,0}
$\endgroup$
4
  • 2
    $\begingroup$ I presume you are already aware that c + a is automatically converted to a + c? $\endgroup$ Commented Dec 23, 2021 at 14:19
  • $\begingroup$ @J.M. Yes, this is just a toy example $\endgroup$
    – Slayer147
    Commented Dec 23, 2021 at 14:20
  • 2
    $\begingroup$ Mathematica consider Xi the "first" term in Psi*Zeta+Xi and not Psi*Zeta $\endgroup$
    – Nasser
    Commented Dec 23, 2021 at 14:21
  • $\begingroup$ @Nasser I edited it $\endgroup$
    – Slayer147
    Commented Dec 23, 2021 at 14:26

2 Answers 2

6
$\begingroup$

In this case the list would be just list2={a,c,Xi,0}

For this example you show, this should it do it. But I do not know if this will fail or not for other examples. If you can provide more examples, it will help test it. These parsing things can be tricky depending on input

list = {a + b, c + d, Psi*Zeta + Xi, 0};
If[AtomQ[#], #, First[#]] & /@ list

Mathematica graphics

Another example to handle more general cases

list = {a + b, c + d, Psi*Zeta + Xi, 0, Exp[x], Sin[x], 
    x + Sin[x], 1 + Exp[x], x*Sin[x], Sin[x]^2, 1/x + 2, 
   {1, 2, 3}};

If[AtomQ[#] || Length[#] == 1 || Head[#] === Power || 
    Head[#] === List, #, First[#]] & /@ list

Mathematica graphics

ps. This might still fail on some other input. More example will help.

$\endgroup$
2
$\begingroup$

This looks like a case for the (often-overlooked) two-argument form of First:

enter image description here

list = {a + b, c + d, Psi*Zeta + Xi, 0};

First[#, #] & /@ list

{a, c, Xi, 0}

Second example from Nasser's answer with exceptions can be handled using:

listb = {a + b, c + d, Psi*Zeta + Xi, 0, Exp[x], Sin[x], x + Sin[x], 
   1 + Exp[x], x*Sin[x], Sin[x]^2, 1/x + 2, {1, 2, 3}};

listb /. $pat : Except[_Power | _List | _?(Length @ # == 1 &)] :> First[$pat, $pat]

enter image description here

$\endgroup$

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.