Skip to content

Prepend

Status: Stable

documented, exercised by the test suite and/or worked examples, with no known limitations recorded.

Description

Prepend[expr, elem]

adds elem to the beginning of expr.

Examples (6)

Every input below was run against the current Mathilda build and its output recorded.

Basic examples (3)

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

In[2]:= Append[<|"a" -> 1, "b" -> 2|>, "a" -> 9]
Out[2]= <|"b" -> 2, "a" -> 9|>

In[3]:= Prepend[<|"a" -> 1, "b" -> 2|>, "b" -> 9]
Out[3]= <|"b" -> 9, "a" -> 1|>

Applications (3)

In[4]:= Prepend[{2, 3, 4}, 1]
Out[4]= {1, 2, 3, 4}

Works on any head, not just List

In[5]:= Prepend[f[b, c], a]
Out[5]= f[a, b, c]

A rule goes to the front of the association

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

Implementation notes

Algorithm. builtin_prepend builds a new function node with the same head whose first element is a copy of the new element followed by copies of all original arguments. Two-argument form only; returns NULL if the first argument is an atom. (PrependTo is the mutating variant that writes the result back to a symbol's OwnValue.)

  • As in Mathematica 15, an existing entry with the same key is moved: it is removed from its old position and the new value is placed at the end (Append) or the front (Prepend).
  • A non-rule element leaves Append/Prepend unevaluated; AppendTo[a, 5] assigns the unevaluated Append[a, 5], exactly like Mathematica.
  • O(n + m): membership is tested through an indexed association of the new rules.

Attributes: none registered.

References

See also: Append

Notes & additional examples

Notes

Prepend adds the element at the front while keeping the original head, so it is not restricted to lists. For an association the argument must be a rule (or rules); it is placed first, and if its key already exists the old entry is dropped from its former position. Append is the tail-side counterpart.