1from itertools import product2S = list(product('HT', repeat=3))3X = [w.count('H') for w in S]4sum(X) / len(S)HHHHHTHTHHTTTHHTHTTTHTTTX=0X=1X=2X=3E[X] = 1.50
Outcome cells: the outcome on top, its probability or its X belowBlocks: each outcome adds 1/8 to the column of its valueCalculator: the running total of the current sumPython card: lists the sample space and averages XThree fair coin flips. The eight outcome cells are the sample space; each shows its probability, 1/8, and then its value of X, the number of heads. Each outcome hops onto the column for its X and drops a 1/8 block, so the columns grow to 1, 3, 3 and 1 blocks: the distribution of X. Tokens then carry value × probability into the calculator, which adds them to E[X] = 1.5, and the wedge marks that balance point. The number of heads in n fair flips follows the binomial distribution, with E[X] = n/2 and Var(X) = n/4. For n = 3 that gives 1.5 and 0.75.

Random variables

  1. Flip a fair coin three times. There are 2 × 2 × 2 = 8 possible outcomes, from HHH to TTT. All are equally likely, so each has probability 1/8. The set of every outcome is the sample space.

Distributions

Expectation

Spread and samples

Try it in the Python prompt

;; step 1/10 · Three flips, eight outcomes
>>> from itertools import product
>>> S = list(product('HT', repeat=3))
>>> len(S), S[0], S[-1]
(8, ('H', 'H', 'H'), ('T', 'T', 'T'))

Capital X names the random variable; small x stands for one of its values. P(X = x) is the probability that X takes the value x. Linearity of expectation, E[X + Y] = E[X] + E[Y], holds for any random variables, even ones that depend on each other. Variances only add like this when the variables are independent.