Split


The usage message for Split and demonstrations of it are shown in the next
few cells.

? Split

Split[list] splits list into sublists consisting of runs of   identical elements. Split[li ... t elements as   identical whenever applying the function test to them yields True. More…

Clear["Global`*"] ;  Split[{a, a, b, b, b, b, a, b, a, a, b, b, b, a}]

{{a, a}, {b, b, b, b}, {a}, {b}, {a, a}, {b, b, b}, {a}}

Many of the most useful applications of Split require providing Split a  test function as a second argument. In the next cell Slit Split considers two  adjacent elements of (lst) "identical" if they are both less than 100 or if  they are both greater or equal to 100. For an explanation of the # & notation  see the discussion of Function.

lst = {10, 11, 100, 234, 648, 467, 12, 13, 14, 356, 15, 16, 457} ;   Split[lst, #1<100 === #2<100&]

{{10, 11}, {100, 234, 648, 467}, {12, 13, 14}, {356}, {15, 16}, {457}}


The next cell sorts (lst) and returns a list of lists where the first sublist
is the elements between 0, 10. The second sublist is the elements between 10
and 20. The third and fourth sublists are the elements from 20 to 30 and from
30 to 40.


lst={8.06833, 32.1809, 20.357, 22.7313, 38.2098, 48.3307,

34.9967, 13.2429, 24.3229, 1.89359, 41.7259, 10.4685,

26.4448, 41.3348, 46.9688};



Split[Sort[lst],Floor[#1/10]===Floor[#2/10]&]

{{1.89359, 8.06833}, {10.4685, 13.2429}, {20.357, 22.7313, 24.3229, 26.4448}, {32.1809, 34.9967, 38.2098}, {41.3348, 41.7259, 46.9688, 48.3307}}


Finally Split can be used on expressions that don't have the head List.  This
is demonstrated in the next cell.

Split[h[a, a, b, b, b, b, a, b, a, a, b, b, b, a]]

h[h[a, a], h[b, b, b, b], h[a], h[b], h[a, a], h[b, b, b], h[a]]


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page