Skip to content
AgileLogics
6 min read

Working with Lists

Prerequisites: Lists

The Wolfram Language has a function for almost every list operation. Learning the common ones saves a lot of code.

Statistics

data = {4, 8, 15, 16, 23, 42};
Total[data]
Mean[data]
Median[data]
Max[data]
N[Mean[data]]
StandardDeviation[{2., 4, 4, 4, 5, 5, 7, 9}]
108
18
31/2
42
18.
2.13809

Mean and Median return exact results for exact data — 31/2 is the middle of 15 and 16. 18. is the approximate number 18.

Sorting and searching

Sort[{3, 1, 2}]
Sort[{3, 1, 2}, Greater]
Reverse[{1, 2, 3}]
MemberQ[{1, 2, 3}, 2]
Count[{1, 2, 1, 3, 1}, 1]
Position[{a, b, a}, a]
Select[Range[10], EvenQ]
{1, 2, 3}
{3, 2, 1}
{3, 2, 1}
True
3
{{1}, {3}}
{2, 4, 6, 8, 10}

Select[list, test] keeps the elements for which test gives True. Functions ending in Q (EvenQ, PrimeQ, MemberQ, StringQ) are predicates — they answer True or False.

Counting and removing duplicates

Tally[{a, b, a, c, a}]
DeleteDuplicates[{3, 1, 3, 2, 1}]
Union[{3, 1, 3, 2, 1}]
{{a, 3}, {b, 1}, {c, 1}}
{3, 1, 2}
{1, 2, 3}

DeleteDuplicates keeps the original order; Union also sorts.

Reshaping

Join[{1, 2}, {3}, {4, 5}]
Partition[Range[6], 2]
Flatten[{{1, 2}, {3, {4}}}]
Transpose[{{1, 2, 3}, {4, 5, 6}}]
Take[Range[10], 3]
Drop[Range[10], 7]
{1, 2, 3, 4, 5}
{{1, 2}, {3, 4}, {5, 6}}
{1, 2, 3, 4}
{{1, 4}, {2, 5}, {3, 6}}
{1, 2, 3}
{8, 9, 10}

Running totals and differences

Accumulate[{1, 2, 3, 4}]
Differences[{1, 4, 9, 16}]
{1, 3, 6, 10}
{3, 5, 7}

Practice

From Range[50], keep the primes, then find how many there are and their total.

Show solution
primes = Select[Range[50], PrimeQ];
Length[primes]
Total[primes]
15
328