Function Repository Resource:

SplitAtPositions

Source Notebook

Split a list at specific indices

Contributed by: Sjoerd Smit

ResourceFunction["SplitAtPositions"][lst,{i1,i2,}]

splits lst into a list of sublists, creating a split before each index ik.

ResourceFunction["SplitAtPositions"][lst,ind,After]

splits after each index instead.

ResourceFunction["SplitAtPositions"][lst,ind,Before]

is equivalent to ResourceFunction["SplitAtPositions"][lst,ind].

Details

All indices should be positive and smaller or equal to Length[lst].
Indices will be sorted first and duplicate indices will be ignored.
ResourceFunction["SplitAtPositions"][list,{}] returns {list}.
ResourceFunction["SplitAtPositions"][{},{i1,}] always fails.
The returned list of lists will never contain an empty list. Because of this, ResourceFunction["SplitAtPositions"][{},{}] returns {}.

Examples

Basic Examples (3) 

Split before indices 2 and 5 so that the sublists after the initial one start at these indices:

In[1]:=
ResourceFunction["SplitAtPositions"][Range[10], {2, 5}]
Out[1]=

Split after instead of before so that the sublists now end on these indices:

In[2]:=
ResourceFunction["SplitAtPositions"][Range[10], {2, 5}, After]
Out[2]=

Explicitly specify to split before each index:

In[3]:=
ResourceFunction["SplitAtPositions"][Range[10], {2, 5}, Before]
Out[3]=

Scope (5) 

If the list of indices is empty, the original list will be returned with an extra list around it:

In[4]:=
ResourceFunction["SplitAtPositions"][Range[5], {}]
Out[4]=

The returned list does not contain empty lists, however:

In[5]:=
ResourceFunction["SplitAtPositions"][{}, {}]
Out[5]=

Splitting the empty list always fails if the index list is not empty:

In[6]:=
ResourceFunction["SplitAtPositions"][{}, {1}]
Out[6]=

Splitting before 1 has no effect on the initial sublist:

In[7]:=
ResourceFunction["SplitAtPositions"][Range[10], {1, 5}, Before]
Out[7]=
In[8]:=
ResourceFunction["SplitAtPositions"][Range[10], {5}, Before]
Out[8]=

Similarly, splitting after the last element does nothing:

In[9]:=
ResourceFunction["SplitAtPositions"][Range[10], {5, 10}, After]
Out[9]=
In[10]:=
ResourceFunction["SplitAtPositions"][Range[10], {5}, After]
Out[10]=

Splitting at non-existing indices returns $Failed. Negative indices are not supported:

In[11]:=
ResourceFunction["SplitAtPositions"][Range[10], {12}]
Out[11]=
In[12]:=
ResourceFunction["SplitAtPositions"][Range[10], {0}]
Out[12]=
In[13]:=
ResourceFunction["SplitAtPositions"][Range[10], {-5}]
Out[13]=

Properties and Relations (1) 

SplitAtPositions[expr,{n},After] is equivalent to TakeDrop[expr,n]:

In[14]:=
ResourceFunction["SplitAtPositions"][Range[10], {3}, After]
Out[14]=
In[15]:=
TakeDrop[Range[10], 3]
Out[15]=

Publisher

Sjoerd Smit

Version History

  • 2.0.0 – 03 May 2022
  • 1.0.0 – 18 April 2022

Related Resources

License Information