21

I want to turn a sum like this

sum =a-b+c+d

Into a List like this:

sumToList[sum]={a,-b,c,d}

How can I achieve this?

Emerson
  • 1,217
  • 10
  • 13
  • 2
    I am a professor of "vectorial analysis" in Mexico. I try to teach the subjects with the use of "Mathematica". I solved a problem seeing this page and also this: http://mathematica.stackexchange.com/questions/100758/finding-scalar-potential-function/100763 ... in which I was not allowed to comment. This was what I did to find the "scalar potential function". https://i.stack.imgur.com/ugIlP.png – David Gardea Feb 06 '17 at 17:43
  • @David I converted your answer to a comment, as it seems more appropriate as such. I know that new users do not have the "privilege" to comment everywhere (a "spam" control measure I believe) but if you continue to participate you will find that you soon do. – Mr.Wizard Feb 06 '17 at 19:12

3 Answers3

27
List @@ sum

{a, -b, c, d}

From the docs on Apply (@@):

f@@expr replaces the head of expr by f.

So List@@sum replaces Head[sum] (that is, Plus) with List.

You can also get the same result by changing 0th Part of sum (which is its Head) to List:

sum[[0]] = List; sum

{a, -b, c, d}

kglr
  • 394,356
  • 18
  • 477
  • 896
  • 2
    There is a slight hiccup that you can encounter using this. If you're not explicitly doing a sum, you will list over whatever the head of the function is. e.g. List @@ 2*3 will result in {2,3} – Alex DB Feb 10 '17 at 17:10
  • @AlexDB, you are right; List@@expr does change the head of expr, whatever it is, to List. – kglr Feb 10 '17 at 17:16
  • 2
    So what's the most general way to make a list, so that we include both distinct cases where there is one and multiple terms? – hal Aug 07 '20 at 18:30
12

Try :

a - b + c + d /. Plus -> List

You can have a look at a - b + c + d //FullForm to see why this works.

b.gates.you.know.what
  • 20,103
  • 2
  • 43
  • 84
7

Still another route:

Last[CoefficientArrays[#]] Variables[#] &[a - b + c + d]
   {a, -b, c, d}
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574