Tally

Tally

Tally[ list ] counts how often each element occurs in a list.

Usages

Tally[ list ]

Tally[ list ] returns a list of pairs {element, count}: one pair for each different element of list, with the number of times it occurs. The pairs are in the order in which the elements first appear in list.

Example in out
Count the letters. b comes first, because it is the first element of the list. Tally[ {b,a,b,c,d,a} ] { {b, 2}, {a, 2}, {c, 1}, {d, 1} }
Count the numbers. Tally[ {1, 2, 2, 3, 3, 3} ] { {1, 1}, {2, 2}, {3, 3} }
Get the elements and the counts as separate lists, using Map. T := Tally[{b,a,b,c,d,a}]
k := Map[p -> p[[1]], T]
n := Map[p -> p[[2]], T]
k = {b, a, c, d}
n = {2, 2, 1, 1}
Details
  • Equal elements: elements are counted together if they are the same expression, regardless of the order of terms or factors: Tally[ {x+1, 1+x} ] returns { {x+1, 2} }. Numbers must have the same form: Tally[ {2.4, 12/5} ] returns { {2.4, 1}, {12/5, 1} }. Lists are equal only if their elements are in the same order.
  • Empty list: Tally[ {} ] returns {}.
Invalid input Result
Tally[ 5 ] Left unevaluated: the result is Tally[ 5 ] itself. The argument must be a list.
Tally[ {1,2}, {3} ] Left unevaluated: Tally takes exactly one argument.

See also: Length, FindI, Map