TheAlgorithms/Python · error · ValueError
{N_POPULATION} must be bigger than {N_SELECTED}
Error message
{N_POPULATION} must be bigger than {N_SELECTED} What it means
Raised by basic() in genetic_algorithm/basic_string.py when N_POPULATION < N_SELECTED. The selection step picks N_SELECTED parents from the population each generation; selecting more individuals than exist would either crash the random sampler or destroy the gene pool, so the function validates this precondition first.
Source
Thrown at genetic_algorithm/basic_string.py:125
Traceback (most recent call last):
...
ValueError: ['e'] is not in genes list, evolution cannot converge
>>> genes.remove("s")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's'] is not in genes list, evolution cannot converge
>>> genes.remove("t")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge
"""
# Verify if N_POPULATION is bigger than N_SELECTED
if N_POPULATION < N_SELECTED:
msg = f"{N_POPULATION} must be bigger than {N_SELECTED}"
raise ValueError(msg)
# Verify that the target contains no genes besides the ones inside genes variable.
not_in_genes_list = sorted({c for c in target if c not in genes})
if not_in_genes_list:
msg = f"{not_in_genes_list} is not in genes list, evolution cannot converge"
raise ValueError(msg)
# Generate random starting population.
population = []
for _ in range(N_POPULATION):
population.append("".join([random.choice(genes) for i in range(len(target))]))
# Just some logs to know what the algorithms is doing.
generation, total_population = 0, 0
# This loop will end when we find a perfect match for our target.
while True:
generation += 1
total_population += len(population)View on GitHub (pinned to f5988cc097)
Solutions
- Ensure N_POPULATION > N_SELECTED; a common healthy ratio is population 5-10x selected.
- Re-read the defaults in the module (300 vs 50) before overriding only one of them.
- Scale both together: if you shrink population to 50, drop selected to ~10.
Example fix
# before
basic('test', ascii_letters, N_POPULATION=50, N_SELECTED=100) # inverted
# after
basic('test', ascii_letters, N_POPULATION=200, N_SELECTED=50) Defensive patterns
Strategy: validation
Validate before calling
if N_POPULATION <= N_SELECTED:
raise ValueError(
f'need N_POPULATION > N_SELECTED, got {N_POPULATION} <= {N_SELECTED}'
)
basic(target, genes, N_POPULATION, N_SELECTED) Try / catch
try:
basic('test', genes, pop, sel)
except ValueError as exc:
if 'must be bigger' in str(exc):
sel = max(1, pop // 4)
basic('test', genes, pop, sel)
else:
raise Prevention
- Keep the population/selected ratio explicit in config comments.
- Change hyperparameters in pairs, never population alone.
When it happens
Trigger: Calling basic('test', genes, N_POPULATION=100, N_SELECTED=200) or via the module defaults (N_POPULATION=300, N_SELECTED=50 — safe) with custom values where selected exceeds population.
Common situations: Tuning GA hyperparameters and shrinking the population for speed while leaving selection pressure high, or swapping the two values when calling.
Related errors
- {not_in_genes_list} is not in genes list, evolution cannot c
- Expected a_coeffs to have {self.order + 1} elements for {sel
- n must not be negative
- Candidates list should not be empty
- Depth cannot be less than 0
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/aadd245b29336135.
Report an issue: GitHub.