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 (3) 

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 (1) 

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

Version History

  • 2.0.0 – 02 March 2020
  • 1.0.0 – 10 January 2019

Related Resources

License Information