Function Repository Resource:

Pop

Source Notebook

Remove and return an element of an expression

Contributed by: Ian Ford

ResourceFunction["Pop"][x]

deletes the last element in the value of x, returns it and resets x to the result.

ResourceFunction["Pop"][x,n]

pops the element at position n from x. If n is negative, the position is counted from the end.

ResourceFunction["Pop"][x,{i,j,}]

pops the part at position {i,j,}.

ResourceFunction["Pop"][x,{{i1,j1,},{i2,j2,}}]

pops parts at several positions.

Details and Options

ResourceFunction["Pop"] has attribute HoldFirst.
ResourceFunction["Pop"][x] is equivalent to ResourceFunction["Pop"][x,-1].
ResourceFunction["Pop"][x,pos] sets x equal to the value of Delete[x,pos] and returns the original value of Extract[x,pos].
Popping the head of a particular element from x sets it equal to the result of applying FlattenAt to the value of x at that point and returns the head.
Popping the head from x makes the head be Sequence and returns the head.
Popping position {} from x sets the value to Sequence[] and returns the original value.
ResourceFunction["Pop"] works on SparseArray objects.
ResourceFunction["Pop"] works on associations, removing elements with the specified keys and returning them.

Examples

Basic Examples (3) 

Assign x to a List:

In[1]:=
x = Alphabet[]
Out[1]=

Pop the last element of the list:

In[2]:=
ResourceFunction["Pop"][x]
Out[2]=

The value assigned to x has changed:

In[3]:=
x
Out[3]=

Pop the element at position 3:

In[4]:=
ResourceFunction["Pop"][x, 3]
Out[4]=
In[5]:=
x
Out[5]=

Pop at position 2 from the end:

In[6]:=
ResourceFunction["Pop"][x, -2]
Out[6]=
In[7]:=
x
Out[7]=

Pop at positions 1 and 3:

In[8]:=
ResourceFunction["Pop"][x, {{1}, {3}}]
Out[8]=
In[9]:=
x
Out[9]=

Pop from a 2D array:

In[10]:=
x = {{a, b}, {c, d}}
Out[10]=
In[11]:=
ResourceFunction["Pop"][x, {2, 1}]
Out[11]=
In[12]:=
x
Out[12]=

Pop from an Association:

In[13]:=
x = <|a -> b, "a" -> c|>
Out[13]=
In[14]:=
ResourceFunction["Pop"][x]
Out[14]=
In[15]:=
x
Out[15]=
In[16]:=
ResourceFunction["Pop"][x, Key[a]]
Out[16]=
In[17]:=
x
Out[17]=

Scope (1) 

Pop works on sparse arrays:

In[18]:=
x = SparseArray[{{i_, i_} -> i}, 3]
Out[18]=
In[19]:=
ResourceFunction["Pop"][x]
Out[19]=
In[20]:=
x
Out[20]=

Properties and Relations (3) 

Popping the head of a whole expression makes the head be Sequence:

In[21]:=
x = {a, b, c}
Out[21]=
In[22]:=
ResourceFunction["Pop"][x, 0]
Out[22]=
In[23]:=
x
Out[23]=

Popping at an empty list of positions does not change the value:

In[24]:=
x = h[a, b]
Out[24]=
In[25]:=
ResourceFunction["Pop"][x, {}]
Out[25]=
In[26]:=
x
Out[26]=

Popping at position {} pops the whole expression:

In[27]:=
x = h[a, b]
Out[27]=
In[28]:=
ResourceFunction["Pop"][x, {{}}]
Out[28]=
In[29]:=
x
Out[29]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 04 December 2018

License Information