Function Repository Resource:

FirstRest

Source Notebook

Conveniently get both the first and remaining elements

Contributed by: Jesse Friedman and Michael Sollami

ResourceFunction["FirstRest"][expr]

returns a list containing the first element and the remaining elements of expr.

ResourceFunction["FirstRest"][expr,def]

returns the first and remaining elements, or def otherwise, and the rest of the list.

Details and Options

Similarly to First, if expr has no first element, a default value may be provided with a second argument.

Examples

Basic Examples (3) 

Take the First and the Rest of a list:

In[1]:=
ResourceFunction["FirstRest"][{1}]
Out[1]=
In[2]:=
ResourceFunction["FirstRest"][Range[10]]
Out[2]=

Apply FirstRest to objects like SparseArray or NumericArray:

In[3]:=
ResourceFunction[
 "FirstRest"] /@ {SparseArray[Range@100], NumericArray[Range@100, "UnsignedInteger8"]}
Out[3]=

FirstRest is useful for starting a fold-like operation:

In[4]:=
FoldList[f] @@ ResourceFunction["FirstRest"][{x, a, b, c}]
Out[4]=

Scope (2) 

FirstRest works on arbitrary expressions:

In[5]:=
ResourceFunction["FirstRest"][f[1, 2, 3, 4]]
Out[5]=

FirstRest will return only the first value (not key) when given an Association:

In[6]:=
ResourceFunction["FirstRest"][<|"a" -> 1, "b" -> 2, "c" -> 3|>]
Out[6]=

Possible Issues (1) 

FirstRest returns an empty list if First fails and no default is provided:

In[7]:=
ResourceFunction["FirstRest"] /@ {1., \[Pi], "abc"}
Out[7]=
In[8]:=
ResourceFunction["FirstRest"][#, Subscript["def", #]] & /@ {1., \[Pi],
   "abc"}
Out[8]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 28 May 2020

Related Resources

License Information