Sub topic 5
Assigning recipients to variants at random
This chapter assumes you know what a hypothesis and a primary metric are (covered earlier in this tutorial). It also assumes you can read short Python snippets. Here you will learn how to split a list into variant groups so that the only systematic difference between the groups is the variant itself.
Why random assignment matters
An A/B test is a causal claim: "the subject line caused the difference in clicks." That claim only holds if the groups were comparable before the email went out. Random assignment makes them comparable. Every trait that affects clicking is spread across the groups by chance alone. This includes traits you can measure (country, signup date) and traits you can't (mood, how busy someone is this week).
Compare that with splitting the list by hand:
- Alphabetical halves (A–M and N–Z) can differ by language, region, or name origin.
- "First half of the file" often means the oldest subscribers, who behave differently from recent ones.
- "Engaged users get A, the rest get B" builds the bias into the test.
In each case, any lift you see could come from the group, not the variant. This is selection bias, and no later statistics can remove it.
The unit of randomization
Decide first what you are randomizing. For email, the unit is almost always the person, not the message. If you assign per send, one person can see variant A on Tuesday and variant B on Thursday, and their responses become tangled.
Pick one stable identifier and use it everywhere:
- A customer ID is the best choice because it survives email changes.
- A lowercased, trimmed email address works if you have nothing better.
- Deduplicate the list before assigning. If
[email protected]and[email protected]are both on the list, they may land in different groups, and one person receives both variants.
Hash-based assignment
There are two common ways to assign at random. The first shuffles the list and cuts it into pieces. The second computes the variant from the recipient's ID with a hash function. A hash function turns any input into a fixed-length, effectively unpredictable number, and always returns the same number for the same input.
Hash-based assignment has useful properties:
- It is reproducible. You can recompute any person's variant later without storing a table.
- It works for people who arrive during the test, such as new signups.
- It needs no shared state, so two systems can agree on a variant independently.
import hashlib
def assign_variant(user_id, experiment, variants=("A", "B")):
key = f"{experiment}:{user_id}".encode("utf-8")
digest = hashlib.sha256(key).hexdigest()
return variants[int(digest, 16) % len(variants)]
print(assign_variant("user-123", "subject-test-2026-11"))Two details matter here.
- The experiment name is part of the key. Without it, the same people would always fall in group A, in every test you ever run. Then any quirk of that group would repeat in every result. Salting with the experiment name gives each test an independent split.
- Use a real hash, not Python's built-in
hash(). For strings,hash()is randomized per process, so the same user gets different variants on different runs.hashlibis stable across machines and runs.
Unequal splits and holdouts
Sometimes you want a split other than 50/50. Examples are a 10/10/80 test-and-send-winner layout (covered in a later chapter) or a holdout that never receives the campaign. To support weights, convert the hash to a number between 0 and 1 and compare it to cumulative cutoffs.
import hashlib
def bucket(user_id, experiment):
key = f"{experiment}:{user_id}".encode("utf-8")
digest = hashlib.sha256(key).digest()
return int.from_bytes(digest[:8], "big") / 2**64
def assign_weighted(user_id, experiment, weights):
# weights: list of (name, share); shares must sum to 1.0
x = bucket(user_id, experiment)
cumulative = 0.0
for name, share in weights:
cumulative += share
if x < cumulative:
return name
return weights[-1][0] # guards against floating-point rounding
plan = [("A", 0.1), ("B", 0.1), ("rest", 0.8)]
print(assign_weighted("user-123", "subject-test-2026-11", plan))The bucket value is uniform between 0 and 1, so a share of 0.1 sends about 10% of the list to that group. Keep the shares fixed once the test starts. If you change them midway, the early and late recipients are no longer drawn the same way.
The assignment process
Do the exclusions before assignment, not after. If you remove unsubscribed or bounced addresses after the split, you may remove more people from one group than the other and unbalance it.
Checking that the split worked
Random does not mean exactly equal. With 40,000 recipients and a 50/50 plan, you will not get exactly 20,000 per group. But a large gap means something is broken. A mismatch between planned and observed group sizes is called a sample ratio mismatch (SRM). Typical causes are a bug in the assignment code, a filter that drops one variant's recipients, or an ID format that differs between systems.
You can test group sizes with the same normal approximation used in the significance chapter. This version checks a two-way 50/50 split.
from math import sqrt
from statistics import NormalDist
def srm_check(n_a, n_b):
n = n_a + n_b
z = (n_a - n / 2) / sqrt(n * 0.25)
p_value = 2 * (1 - NormalDist().cdf(abs(z)))
return z, p_value
z, p = srm_check(20180, 19820)
print(f"z={z:.2f} p={p:.4f}")A common convention is to treat a p-value below 0.001 as a real mismatch. Use a strict cutoff because you run this check on every test, and a loose one would raise false alarms constantly. If the check fails, do not read the results. Find the cause, fix it, and rerun the test.
Balance on known traits
Random assignment balances traits on average, but a single split can still be lopsided on something important, especially in small lists. After assigning, compare the groups on a few traits that you expect to affect the outcome: country, signup year, past click rate, device type.
If a trait is clearly unbalanced, two fixes are common:
- Reassign with a new experiment salt (for example, add
-v2) before sending, and check again. Do this only before launch and only for a documented reason. Rerunning until the result looks good is a form of cheating. - Stratify. Split the list into strata, such as by country or by past engagement, and randomize inside each stratum. Each stratum then contributes equally to every variant. With hashing, run
assign_variantper stratum with the stratum name added to the experiment key.
Stratifying is most useful when one trait strongly predicts the outcome. Past engagement is the usual example, because heavy clickers and non-clickers behave very differently and both can end up concentrated in one group.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Splitting by list order or alphabet | Groups differ systematically | Hash the ID |
| Same salt for every test | Same people always in A | Include the experiment name |
| Duplicates not removed | One person gets both variants | Normalize and deduplicate first |
| Exclusions applied after assignment | Group sizes drift apart | Filter first, assign second |
| Reassigning until the groups "look right" | Hidden selection | Decide checks in advance; reassign only for documented reasons |
| Changing weights mid-test | Early and late recipients are not comparable | Freeze the plan at launch |
| Analyzing only people who opened | Opening depends on the variant | Analyze everyone assigned |
The last row deserves emphasis. The analysis population is everyone you assigned, whether or not they opened or even received the email. This is called intent-to-treat analysis. Dropping non-openers throws away the randomization, because a subject line can change who opens.
Randomizing send times
In a send-time test, the variant is the delivery slot, and the principle is the same: assign each person to a slot at random, then send each group at its slot. Do not put all of one time zone in "morning" and another in "evening," because then timing is mixed with audience. The next chapters cover this in detail. For now, keep it in mind: whatever differs between groups must be the variant and nothing else.
Exercise
A teammate splits the list by taking the first 20,000 rows of a file as variant A and the next 20,000 as variant B. The file is ordered by signup date. Give two reasons this is not a valid random split, and name a method that fixes it.
Show answer
Rows ordered by signup date mean variant A holds the oldest subscribers and variant B the newest, so any difference in clicks could come from tenure rather than the subject line (selection bias). The split also cannot be reproduced or audited from a stated rule, and it cannot place late arrivals consistently. Hash the normalized recipient ID together with the experiment name and map the result to a variant, then run an SRM check on the group sizes.
Exercise
You run assign_variant for two different experiments, "subject-test-a" and "subject-test-b", on the same list. Roughly what fraction of users who got "A" in the first test also get "A" in the second, and why?
Show answer
About half. Because the experiment name is part of the hash key, the two splits are independent, so group membership in the first test says nothing about membership in the second. If the experiment name were left out, the overlap would be 100%.