WolframLang: List Order Functions

By Xah Lee. Date: . Last updated: .

Function related to ordering of a list.

Sort
  • Sort[list]
  • Sort[list, p]

sort a list or any expression.

p is the ordering function that takes 2 args and returns one of {1, 0, -1} or {True, False} .

Sort

Sort[ {3, 5, 2} ] === {2, 3, 5}

Sort[ {"cat", "dog", "bird"} ] === {"bird", "cat", "dog"}
(* sort by second number *)

Sort[
 {{10, 3}, {20, 2}, {30, 1}},
 Function[{a,b}, a[[2]] < b[[2]] ]
] ===
{{30, 1}, {20, 2}, {10, 3}}
SortBy
  • SortBy[list, f]
  • SortBy[list, {f1, f2, etc}]
  • SortBy[list, f, p]

Sort by applying f to items and compare the result. For example, f returns a integer. When there is a list of f, each successive one is used to break the tie.

predicate p (the ordering function) can be used, after the output of f

SortBy

(* sort by string length *)

SortBy[
 {"bird", "dog", "cat"},
 StringLength
] === {"cat", "dog", "bird"}
(* note, it also swapped cat and dog, by apply normal sort behavior to string *)
(* sort by second number *)

SortBy[
 {{10, 3}, {20, 2}, {30, 1}},
 Function[{x}, x[[2]] ]
] ===
{{30, 1}, {20, 2}, {10, 3}}
Reverse

Reverse

Ordering
return a list of integers that represent the ordering of the items.

Ordering

Ordering[ {a, c, b} ] === {1, 3, 2}
RotateRight
shift all elements to the right, last item is moved to first.

RotateRight

RotateRight[ {1, 2, 3, 4} ] === {4, 1, 2, 3}
RotateLeft
shift all elements to the left, first item is moved to last.

RotateLeft

List Operations