# Computing Many Differences in a Nested List

Consider a nested list. For example:

{{-1.}, {1.99196}, {-0.787432}, {-1.3562, -1., 1.3562}, {-1.77689}, {1.49709},
{-1.}, {1.13944}, {-0.720512}, {-1., -0.84243, 1.68838}, {-0.667961},
{-1.89495, -0.700922, 1.16473}, {-1.}, {1.21298}, {-0.750015}, {-1., -1., 1.},
{-1.3879}, {1.83929}, {-1.}, {1.19503}, {-1.95681}, {1.26995}, {-1.25905},
{1.}, {-1.}, {1.40958}, {-0.824416}, {-1.6483, -1., 1.}, {-1.59721}, {1.},
{-1., 1., 1.83929}, {0.877628}, {-0.562781}, {-1., -0.578329, 1.91893},
{-0.543689}, {-1.63758, -0.553375, 1.2279}, {-1.58235, -1., -0.631973}}


I am wondering if it is possible to compute the differences of the elements in the lists. For example, if the nested list was just

{{-1.}, {1.99196}, {-0.787432}, {-1.3562, -1., 1.3562}, {-1.77689}, {1.49709},
{-1.}, {1.13944}, {-0.720512}, {-1., -0.84243, 1.68838}}


I would get:

{.3562, 2.3562, 0.15757, 2.53081}.


In other words, I would like the differences of the elements in lists that have more than one element.

I have tried some applications of Differences, but it is not quite working as expected. Any help and/or ideas are immensely appreciated.

• How about Differences /@ list // Flatten? Commented May 24, 2017 at 22:42
• @jjc385 This works wonderfully, thank you! Commented May 24, 2017 at 22:58

It looks like you want to take Differences of all nested lists with more than one element.

list = {{-1.}, {1.99196}, {-0.787432}, {-1.3562, -1., 1.3562}, {-1.77689}, {1.49709}, {-1.}, {1.13944}, {-0.720512},{-1., -0.84243, 1.68838}};

Differences /@ list

{{}, {}, {}, {0.3562, 2.3562}, {}, {}, {}, {}, {}, {0.15757, 2.53081}}


Notice that Differences applied to a singleton list yields {}. You can get rid of the empty lists and flatten this into one list using Flatten :

Differences /@ list // Flatten

{0.3562, 2.3562, 0.15757, 2.53081}


If your list is called L, try:

Differences@Flatten[L/.{_}->Nothing]

I do have an extra element compared to you, though. Is that a mistake on your part, or mine?

• Your mistake. It should be Flatten[Differences /@ (L /. {_} -> Nothing)]` Commented May 25, 2017 at 0:38