Function Repository Resource:

TakeBefore

Source Notebook

Take elements before the specified element in an expression

Contributed by: Wolfram Staff

ResourceFunction["TakeBefore"][list,pattern,n]

takes n elements of list preceding the first occurrence of pattern.

ResourceFunction["TakeBefore"][list,pattern,n,levelspec]

takes elements on levels specified by levelspec.

ResourceFunction["TakeBefore"][pattern,n,]

represents an operator form of ResourceFunction["TakeBefore"] that can be applied to an expression.

Details and Options

ResourceFunction["TakeBefore"] accepts the following elements of the standard sequence specification:
Allall elements
Noneno elements
nelements 1 through n
UpTo[n]up to n elements, as available
ResourceFunction["TakeBefore"] can be used on an object with any head, not necessarily List.
levelspec can be specified using the standard level specification, as used, for instance, in Cases.
The default value for levelspec in ResourceFunction["TakeBefore"] is {1}.
With the option setting HeadsTrue, ResourceFunction["TakeBefore"] looks at heads of expressions and their parts.
ResourceFunction["TakeBefore"][pattern,n,][list] is equivalent to ResourceFunction["TakeBefore"][list,pattern,n,].

Examples

Basic Examples (5) 

Take the two elements before the element d in a list:

In[1]:=
list = {a, b, c, d, e, f};
In[2]:=
ResourceFunction["TakeBefore"][list, d, 2]
Out[2]=

Do the same using the operator form of TakeBefore:

In[3]:=
ResourceFunction["TakeBefore"][d, 2]@list
Out[3]=

Take all elements before b:

In[4]:=
ResourceFunction["TakeBefore"][{a, b, c, d, e, f}, b, All]
Out[4]=

Take elements from an expression with an arbitrary head:

In[5]:=
ResourceFunction["TakeBefore"][foo[a, b, c, d, e, f], d, 2]
Out[5]=

Take as many elements as possible, up to 20:

In[6]:=
ResourceFunction["TakeBefore"][{a, b, c, d, e, f}, d, UpTo[20]]
Out[6]=

Take the first three elements before the element e at level 2:

In[7]:=
ResourceFunction["TakeBefore"][{{a, b}, {c, d}, {e, f}}, e, 3, {2}]
Out[7]=

Options (2) 

Heads (2) 

By default, TakeBefore does not include the head of an expression when creating a list of elements to match against the specified pattern:

In[8]:=
ResourceFunction["TakeBefore"][{a, a[], b, b[]}, b, UpTo[2], {-1}]
Out[8]=

Use the option Heads to include expression heads:

In[9]:=
ResourceFunction["TakeBefore"][{a, a[], b, b[]}, b, UpTo[2], {-1}, Heads -> True]
Out[9]=

Version History

  • 1.0.0 – 02 August 2019

Related Resources

License Information