Measure monotonic association by ranking each list then applying the rank-difference formula: r = 1 − 6Σd²/(n(n²−1)), valid only when all ranks are distinct (no ties). Assign 1-based ranks via sorted-order lookup, compute d = rx[i] − ry[i] for each pair, sum d². With scipy, spearmanr(x, y).statistic; p-value snapshot-only.

By hand

With the library

scipy.stats.spearmanr(x, y) computes Spearman r internally (rank then Pearson). .statistic is the r value; .pvalue is the two-tailed p-value for H₀: r=0, shown in snapshot but not in the RESULT comparison.

naive.py
x = [2, 4, 1, 5, 3]
y = [1, 3, 2, 5, 4]
n = len(x)
sx = sorted(x)
sy = sorted(y)
rx = []
for v in x:
    rx.append(sx.index(v) + 1)
ry = []
for v in y:
    ry.append(sy.index(v) + 1)
sum_sq_d = 0
for i in range(n):
    d = rx[i] - ry[i]
    sum_sq_d = sum_sq_d + d * d
r = 1 - 6 * sum_sq_d / (n * (n ** 2 - 1))
print('RESULT:', round(r, 4))
library.py
from scipy.stats import spearmanr
from dalib.display import set_display
set_display()

x = [2, 4, 1, 5, 3]
y = [1, 3, 2, 5, 4]
result = spearmanr(x, y)
r = result.statistic
p = result.pvalue
print('r:', round(r, 4))
print('p-value:', round(p, 4))
print('RESULT:', round(r, 4))
r: 0.8
p-value: 0.1041
RESULT: 0.8

Honesty

This lesson shows the computation exactly, on a tiny pinned sample. The arithmetic is correct and reproducible, but with a sample this small the result is not a valid statistical finding — it demonstrates the mechanism, not evidence. Real inference needs an adequate sample size and assumption checks (e.g. independence and continuity of the underlying distribution); the p-value / interval here should be read as "how the formula is computed," not as a conclusion about a population.

Implementation notes

  • The formula 1−6Σd²/(n(n²−1)) is algebraically equivalent to Pearson r on the ranks, but only when all ranks are distinct. With ties you must use averaged ranks and Pearson r on those averages — the simple formula no longer holds.
  • Spearman r captures monotonic relationships (x rising as y rises, even non-linearly), not just linear ones. Pearson r can be 0 while Spearman r is non-zero if the relationship is monotonic but curved.
  • Cross-reference: pearson-correlation (this chapter) for the linear counterpart and the formula that Spearman applies to ranks.