Wolfram Research

Function Repository Resource:

SplitWhen

Source Notebook

Split a list every time an element satisfies a test

Contributed by: Taliesin Beynon

ResourceFunction["SplitWhen"][list,f]

splits list into sublists, splitting after each ei for which f[ei] is True.

Details and Options

ResourceFunction["SplitWhen"] does not work with associations.

Examples

Basic Examples

Split a sequence when an element is even:

In[1]:=
ResourceFunction["SplitWhen"][Table[Fibonacci[n], {n, 20}], EvenQ]
Out[1]=

Split at every occurrence of an element:

In[2]:=
ResourceFunction["SplitWhen"][{x, x, r, b, y, r, c, z}, # == r &]
Out[2]=

Split at every occurrence of an negative integer:

In[3]:=
Split[{2, 0, -1, 4, 2, -1, 1, -2, -1, -4}, Sign[#1] == 1 &]
Out[3]=

Applications

Number of integers to find a prime:

In[4]:=
Length /@ ResourceFunction["SplitWhen"][Range[20], PrimeQ]
Out[4]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information