Skip to main content
added 2 characters in body
Source Link
kglr
  • 400.5k
  • 18
  • 488
  • 929

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

enter image description here

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

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

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

Source Link
kglr
  • 400.5k
  • 18
  • 488
  • 929

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