Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A simple genetic algorithm can be built from a few parts: a way to represent a candidate, a fitness function, parent selection, crossover, mutation, and a stopping rule. This walkthrough uses a binary genome and the OneMax objective, so you can see each step clearly—and avoid a common Python bug in which variation operators change selected parents in place.

What the algorithm does

A genetic algorithm (GA) searches by evolving a population of candidate solutions. It scores candidates with a fitness function, selects parents, creates offspring with variation operators, and repeats until it reaches a stopping condition such as a generation limit or evaluation budget. It is a search method, not a guarantee that every run will find the best possible answer.

For a small example, use OneMax: each candidate is a fixed-length list of zeroes and ones, and its fitness is the sum of its bits. With a 12-bit genome, for example, [1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1] has fitness 6. The maximum possible fitness is 12, achieved by an all-ones genome. DEAP uses OneMax as an illustrative problem in its repository.

A complete from-scratch example

The following implementation uses tournament selection, one-point crossover, and bit-flip mutation. It copies selected parents before changing them, so the current population remains intact while offspring are prepared.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
import random

# Problem and run settings
GENOME_LENGTH = 12
POPULATION_SIZE = 40
GENERATIONS = 50
TOURNAMENT_SIZE = 3
CROSSOVER_PROBABILITY = 0.8
MUTATION_PROBABILITY = 0.02  # Probability for each bit


def make_individual():
    return [random.randint(0, 1) for _ in range(GENOME_LENGTH)]


def fitness(individual):
    return sum(individual)


def tournament_select(population):
    contestants = random.sample(population, TOURNAMENT_SIZE)
    return max(contestants, key=fitness)


def crossover(parent_a, parent_b):
    """Return two children made with one-point crossover."""
    if len(parent_a) < 2:
        return parent_a[:], parent_b[:]
    point = random.randint(1, len(parent_a) - 1)
    child_a = parent_a[:point] + parent_b[point:]
    child_b = parent_b[:point] + parent_a[point:]
    return child_a, child_b


def mutate(individual):
    """Flip each bit independently with MUTATION_PROBABILITY."""
    for index in range(len(individual)):
        if random.random() < MUTATION_PROBABILITY:
            individual[index] = 1 - individual[index]
    return individual


population = [make_individual() for _ in range(POPULATION_SIZE)]
evaluations = len(population)

for generation in range(GENERATIONS + 1):
    best = max(population, key=fitness)
    print(
        f"generation={generation:02d} "
        f"best_fitness={fitness(best)}/{GENOME_LENGTH} "
        f"evaluations={evaluations}"
    )

    if fitness(best) == GENOME_LENGTH or generation == GENERATIONS:
        break

    next_population = [best[:]]  # Elitism: preserve the current best candidate.

    while len(next_population) < POPULATION_SIZE:
        # Selection returns references to members of the existing population.
        parent_a = tournament_select(population)[:]
        parent_b = tournament_select(population)[:]

        if random.random() < CROSSOVER_PROBABILITY:
            child_a, child_b = crossover(parent_a, parent_b)
        else:
            child_a, child_b = parent_a, parent_b

        mutate(child_a)
        mutate(child_b)
        next_population.append(child_a)
        if len(next_population) < POPULATION_SIZE:
            next_population.append(child_b)

    population = next_population
    evaluations += POPULATION_SIZE - 1  # The copied elite needs no new evaluation.

How each part works

Representation and fitness

make_individual() creates a fixed-length binary genome. fitness() assigns a score by counting the ones. For a different problem, these functions must reflect its decision variables and objective; a binary representation is appropriate only when the problem can sensibly be represented with bits.

Tournament selection

tournament_select() samples three candidates and returns the one with the highest fitness. A larger tournament makes selection more competitive because weaker candidates are less likely to win; it does not make a setting universally better. The sample size must not exceed the population size.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Crossover and mutation

One-point crossover chooses a cut between bits and swaps the suffixes of two parents. The mutation function independently flips each bit with probability MUTATION_PROBABILITY. That is a per-bit probability, not the probability that an entire individual mutates. These operators fit binary lists; other representations need compatible operators.

Here, crossover probability is applied once to each parent pair. If the random draw is above the threshold, the copied parents become the children without crossover. Mutation is then attempted for every bit in both children, whether or not crossover occurred.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Replacement, elitism, and stopping

Each iteration fills a new population and then replaces the old one. The first slot is a copy of the best current candidate, an elitism choice that prevents the best fitness from being lost during replacement. The run stops early if the maximum OneMax score is reached; otherwise it ends after the configured number of generations.

The example counts the initial population as evaluated and adds one evaluation for each newly created non-elite individual. Because this objective is inexpensive and deterministic, the code calls fitness() directly rather than storing scores. For costly or stochastic objectives, cache or explicitly recalculate fitness when a genome changes, and count actual objective calls.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Why copying matters in Python

In Python, assigning an object to another variable does not duplicate it. A selection function that returns a population member returns a reference to that same list. If an in-place mutation changes it, the original population member changes too. DEAP explicitly notes that its selection operators return references and that its crossover and mutation operators modify individuals in place; see its operators tutorial.

This example copies each selected parent with [:] before variation, and its crossover function returns new child lists. Those choices isolate offspring from the old population. If you instead write operators that mutate a list in place, copy before passing selected individuals to them. In either design, a changed genome has a changed fitness and must not keep a stale cached score.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose parameters as a starting point, not a recipe

Population size, generation count, selection pressure, crossover, mutation, and replacement policy influence the search. They depend on the representation, objective, and available compute, so this small OneMax example does not establish generally optimal values.

Choice Meaning in this example How to adapt it
Population size 40 candidates Increase it when broader population diversity is useful and the evaluation budget permits; each generation then costs more evaluations.
Tournament size 3 sampled candidates compete Larger tournaments increase selection pressure; compare outcomes over repeated runs rather than assuming one size is best.
Crossover probability 0.8 chance per parent pair Controls whether a pair recombines. Keep it distinct from mutation probability.
Mutation probability 0.02 chance per bit This is a per-gene setting. A probability applied once to an individual would mean something different.
Replacement and elitism New generation replaces the old; one best individual is copied forward Choose whether to preserve top candidates and how many. Elitism protects strong solutions but can reduce diversity if overused.
Stopping condition Maximum score or 50 generations A generation cap is straightforward. An evaluation budget is useful when comparing approaches that evaluate different numbers of candidates.

These are illustrative settings, not recommendations. The DEAP repository, for example, includes a 100-bit OneMax configuration with 300 individuals, 40 generations, crossover probability 0.5, mutation probability 0.1, and per-bit mutation probability 0.05. Those values describe that example only.

Track progress and make runs reproducible

The printed output records the generation, best fitness, and evaluation count. If the best score stops improving, that is useful diagnostic information, but it does not by itself show why progress stalled. Consider also recording average fitness and preserving the best candidate found across the run.

To reproduce a run while debugging, set a seed near the start of the script, such as random.seed(7). The same seed and code make the random choices repeatable in a given Python environment; changing parameters, code, or random-number implementation can change the result. For a fair comparison between settings, run multiple seeds and compare fitness against evaluations, rather than reporting a single favorable run.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common implementation mistakes

  • Mutating the old population unintentionally: copy selected lists before any in-place operator, or design operators to return new lists.
  • Using operators that do not match the genome: bit-flip mutation and one-point crossover are for binary sequences; other representations need suitable operations. DEAP advises checking the behavior of the selected crossover operator in its operator documentation.
  • Confusing mutation probabilities: state whether a rate is per pair, per individual, or per gene. This code uses a pair-level crossover draw and a per-bit mutation draw.
  • Keeping stale fitness: recompute or invalidate a candidate's score after changing its genome if fitness is cached.
  • Comparing runs with different work budgets: generation counts alone can hide different numbers of evaluations. Track evaluations when comparing algorithms or configurations. DEAP's algorithm documentation describes generational evaluation, selection, variation, and reevaluation; the from-scratch handout by Denis Pallez illustrates evaluation budgets and progress observers.

When to use a library instead

Writing the loop yourself is helpful for learning and for a small, customized search. A library becomes useful when you need reusable operators, multiple evolutionary strategies, or established bookkeeping. DEAP's eaSimple documentation lays out a generational sequence of evaluation, stochastic selection, variation, and reevaluation. Its operator guidance also makes the reference and in-place modification behavior explicit, which remains important when adapting library examples.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.