{"id":25715,"date":"2023-02-26T12:53:34","date_gmt":"2023-02-26T07:23:34","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=25715"},"modified":"2026-07-13T12:42:31","modified_gmt":"2026-07-13T07:12:31","slug":"python-genetic-algorithm","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/","title":{"rendered":"Genetic Algorithm in Python: Fitness, Selection, and Mutation"},"content":{"rendered":"<p><strong>Quick answer:<\/strong> A genetic algorithm maintains candidate solutions, evaluates a fitness function, selects parents, creates new candidates through crossover and mutation, and repeats. The objective direction, representation, randomness, stopping rule, and validation experiment determine whether the search is meaningful.<\/p>\n<figure class=\"pythonpool-article-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-b103.png\" alt=\"Python Pool infographic showing a genetic algorithm loop from population fitness to selection, crossover, mutation, and next generation\" width=\"1536\" height=\"1034\" loading=\"lazy\" decoding=\"async\"><figcaption>A genetic algorithm iterates population evaluation and variation; preserve the best candidates deliberately and measure whether the search actually improves the objective.<\/figcaption><\/figure>\n<p>A genetic algorithm is an optimization technique inspired by evolution. It keeps a population of candidate solutions, scores each candidate with a fitness function, selects better candidates, and creates new candidates through crossover and mutation. A genetic search can approximate constrained selection problems, while <a href=\"https:\/\/www.pythonpool.com\/knapsack-problem-python\/\">Knapsack Problem in Python: 3 Solutions<\/a> compares brute force, memoization, and dynamic programming on knapsack directly.<\/p>\n<p>Genetic algorithms are useful when a search space is large, rough, or hard to optimize with direct formulas. They are common in scheduling, feature selection, parameter tuning, route planning, and toy optimization problems where a good solution is enough.<\/p>\n<p>They do not guarantee the perfect answer. Instead, they explore many candidates and try to improve the population over time. That makes them practical for problems where checking a candidate is easier than calculating the best candidate directly.<\/p>\n<p>The <a href=\"https:\/\/deap.readthedocs.io\/en\/master\/\">DEAP documentation<\/a> and <a href=\"https:\/\/pygad.readthedocs.io\/en\/latest\/\">PyGAD documentation<\/a> cover established libraries. This guide uses small pure-Python examples so the moving parts are easy to see. For related array operations, see <a href=\"https:\/\/www.pythonpool.com\/numpy-repeat\/\">NumPy repeat<\/a>.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #990303;color:#990303\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #990303;color:#990303\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Create_A_Candidate\" >Create A Candidate<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Score_Fitness\" >Score Fitness<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Select_Parents\" >Select Parents<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Apply_Crossover\" >Apply Crossover<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Apply_Mutation\" >Apply Mutation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Run_A_Small_Genetic_Algorithm\" >Run A Small Genetic Algorithm<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Best_Practices\" >Best Practices<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Define_A_Candidate_Representation\" >Define A Candidate Representation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Make_Fitness_Direction_Explicit\" >Make Fitness Direction Explicit<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Balance_Selection_Pressure\" >Balance Selection Pressure<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Use_Crossover_And_Mutation_Together\" >Use Crossover And Mutation Together<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Preserve_Good_Candidates_Deliberately\" >Preserve Good Candidates Deliberately<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Repeat_Seeded_Experiments\" >Repeat Seeded Experiments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#Frequently_Asked_Questions\" >Frequently Asked Questions<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#What_is_a_genetic_algorithm\" >What is a genetic algorithm?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#What_is_a_fitness_function\" >What is a fitness function?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#What_do_crossover_and_mutation_do\" >What do crossover and mutation do?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#How_do_I_avoid_a_genetic_algorithm_stopping_too_early\" >How do I avoid a genetic algorithm stopping too early?<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Create_A_Candidate\"><\/span>Create A Candidate<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A candidate is one possible answer. For a simple binary problem, represent each candidate as a list of zeros and ones.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import random\n\ndef make_candidate(length):\n    return [random.randint(0, 1) for _ in range(length)]\n\ncandidate = make_candidate(8)\n\nprint(candidate)\n<\/code><\/pre>\n<\/div>\n<p>Real projects may use numbers, strings, routes, model settings, or custom objects. The representation should make crossover and mutation possible.<\/p>\n<p>Choose the representation carefully because every later step depends on it. A candidate should be easy to score, copy, combine, and change in small ways.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Score_Fitness\"><\/span>Score Fitness<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The fitness function decides how good a candidate is. In this toy example, more ones means a better score.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">def fitness(candidate):\n    return sum(candidate)\n\nprint(fitness([1, 0, 1, 1]))\nprint(fitness([0, 0, 1, 0]))\n<\/code><\/pre>\n<\/div>\n<p>The fitness function is the most important part of the algorithm. If it rewards the wrong behavior, the search will move in the wrong direction.<\/p>\n<p>Good fitness functions are consistent and cheap enough to run many times. If scoring one candidate is expensive, population size and generation count become important performance controls.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Select_Parents\"><\/span>Select Parents<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Selection chooses candidates that will produce the next generation. A simple approach is to keep the highest-scoring candidates.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">def select_parents(population, count):\n    ranked = sorted(population, key=fitness, reverse=True)\n    return ranked[:count]\n\npopulation = [\n    [1, 0, 1, 0],\n    [1, 1, 1, 0],\n    [0, 0, 1, 0],\n]\n\nprint(select_parents(population, 2))\n<\/code><\/pre>\n<\/div>\n<p>Selection pressure controls how strongly the algorithm favors current winners. Too much pressure can reduce diversity too early.<\/p>\n<p>Keeping some variety in the population helps the algorithm explore. If every candidate becomes nearly identical too quickly, crossover and mutation have less useful material to work with.<\/p>\n<p><!-- Python Pool visual layout repair 2026-07-13 --><\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/genetic-population-b193.png\" alt=\"Python Pool infographic showing genetic algorithm individuals, chromosomes, fitness, and a population\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>A genetic algorithm evaluates a population of candidate solutions.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Apply_Crossover\"><\/span>Apply Crossover<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Crossover combines two parents into a child. One-point crossover swaps the tail of two lists after a split point.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">def crossover(left, right):\n    point = len(left) \/\/ 2\n    return left[:point] + right[point:]\n\nparent_a = [1, 1, 0, 0, 1, 0]\nparent_b = [0, 0, 1, 1, 0, 1]\n\nprint(crossover(parent_a, parent_b))\n<\/code><\/pre>\n<\/div>\n<p>Crossover works best when useful building blocks can be shared between candidates. If the representation is poor, crossover may mostly create broken children.<\/p>\n<p>For some problems, a different crossover method is better than a simple halfway split. The operator should respect the structure of the candidate, such as routes, schedules, or parameter ranges.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Apply_Mutation\"><\/span>Apply Mutation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Mutation makes small random changes. It helps the search escape local patterns and keeps the population diverse.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import random\n\ndef mutate(candidate, rate=0.1):\n    child = candidate[:]\n    for index, bit in enumerate(child):\n        if random.random() &lt; rate:\n            child[index] = 1 - bit\n    return child\n\nprint(mutate([1, 1, 1, 1], rate=0.5))\n<\/code><\/pre>\n<\/div>\n<p>A mutation rate that is too high can turn the search into random noise. A rate that is too low may make the population converge too early.<\/p>\n<p>Mutation is the exploration step. It introduces new possibilities that are not present in the selected parents, which can help the search escape a weak local result.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/genetic-selection-b193.png\" alt=\"Python Pool infographic mapping fitness scores through selection to parent candidates\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Selection favors candidates according to the chosen fitness strategy.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Run_A_Small_Genetic_Algorithm\"><\/span>Run A Small Genetic Algorithm<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>This compact loop creates a population, selects parents, creates children, mutates them, and tracks the best candidate.<\/p>\n<div class=\"pythonpool-code-scroll\" style=\"max-width:103%;overflow-x:auto;-webkit-overflow-scrolling:touch;\">\n<pre><code class=\"language-python\">import random\n\ndef run(length=8, size=20, generations=10):\n    population = [make_candidate(length) for _ in range(size)]\n\n    for _ in range(generations):\n        parents = select_parents(population, size \/\/ 2)\n        children = []\n\n        while len(children) &lt; size:\n            left, right = random.sample(parents, 2)\n            child = mutate(crossover(left, right), rate=0.05)\n            children.append(child)\n\n        population = children\n\n    return max(population, key=fitness)\n\nbest = run()\nprint(best, fitness(best))\n<\/code><\/pre>\n<\/div>\n<p>This example is intentionally small. Production genetic algorithms need better selection, stopping rules, constraints, logging, and repeatable random seeds.<\/p>\n<p>Stopping rules can use a fixed generation count, a target score, or a limit on generations without improvement. Logging the best score per generation helps show whether the search is still making progress.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Best_Practices\"><\/span>Best Practices<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Start by defining a clear fitness function and a representation that can be changed safely. Then choose population size, mutation rate, crossover method, and stopping rules. Track the best score over time so you can see whether the search is improving.<\/p>\n<p>Use libraries such as DEAP or PyGAD when you need mature operators, constraints, parallel evaluation, or experiment tooling. Use a hand-written version only when learning, prototyping, or solving a small custom problem.<\/p>\n<p>The reliable pattern is to keep the first version simple, test each operator independently, and measure whether each generation improves the score. A genetic algorithm is useful only when the fitness function and representation match the real optimization goal.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Define_A_Candidate_Representation\"><\/span>Define A Candidate Representation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Choose a chromosome or candidate structure that can express valid solutions. If most random mutations create invalid candidates, add repair or constraint-aware operators instead of hiding failures in the fitness score.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/genetic-mutation-b193.png\" alt=\"Python Pool infographic comparing crossover, mutation, genes, offspring, and diversity\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Crossover and mutation create new candidates while preserving search diversity.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Make_Fitness_Direction_Explicit\"><\/span>Make Fitness Direction Explicit<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Decide whether larger or smaller scores are better and normalize penalties consistently. A sign error can make selection favor the worst candidates while the population still appears to change.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Balance_Selection_Pressure\"><\/span>Balance Selection Pressure<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Strong selection exploits good candidates but can remove diversity early. Tournament, rank, or weighted selection should be tested against population collapse and premature convergence.<\/p>\n<figure class=\"pythonpool-article-visual pythonpool-supporting-visual\"><img src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/genetic-check-b193.png\" alt=\"Python Pool infographic testing fitness design, convergence, randomness, constraints, and validation\" width=\"1536\" height=\"1054\" loading=\"lazy\" decoding=\"async\"><figcaption>Check fitness design, convergence, randomness, constraints, and reproducibility.<\/figcaption><\/figure>\n<h2><span class=\"ez-toc-section\" id=\"Use_Crossover_And_Mutation_Together\"><\/span>Use Crossover And Mutation Together<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Crossover recombines existing structure, while mutation explores new structure. Rates depend on the representation and problem; log them and evaluate sensitivity rather than using one magic constant.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Preserve_Good_Candidates_Deliberately\"><\/span>Preserve Good Candidates Deliberately<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Elitism can retain the best solution, but too much elitism reduces exploration. Keep a copy of the best candidate and verify that it remains valid after every generation.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Repeat_Seeded_Experiments\"><\/span>Repeat Seeded Experiments<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Random search results vary. Run multiple seeds, report best and typical fitness, track generation history, and compare against a simple baseline so one lucky run is not presented as a reliable improvement.<\/p>\n<p>The <a href=\"https:\/\/docs.python.org\/3\/library\/random.html\">official Python random documentation<\/a> covers reproducible generators. Related Python Pool references include <a href=\"https:\/\/www.pythonpool.com\/python-logging\/\">run logging<\/a> and <a href=\"https:\/\/www.pythonpool.com\/python-testing-framework\/\">testing<\/a>.<\/p>\n<p>For related optimization workflows, compare <a href=\"https:\/\/www.pythonpool.com\/python-logging\/\">run histories<\/a>, <a href=\"https:\/\/www.pythonpool.com\/python-testing-framework\/\">seeded tests<\/a>, and <a href=\"1\">randomness<\/a> when evaluating a genetic algorithm.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Frequently_Asked_Questions\"><\/span>Frequently Asked Questions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"What_is_a_genetic_algorithm\"><\/span>What is a genetic algorithm?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>It is a population-based search method that evaluates candidate solutions, selects promising candidates, and creates new candidates through variation.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"What_is_a_fitness_function\"><\/span>What is a fitness function?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The fitness function scores how well a candidate meets the optimization objective; its direction and scale must be defined clearly.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"What_do_crossover_and_mutation_do\"><\/span>What do crossover and mutation do?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Crossover combines parts of parent candidates, while mutation introduces random changes that maintain exploration.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"How_do_I_avoid_a_genetic_algorithm_stopping_too_early\"><\/span>How do I avoid a genetic algorithm stopping too early?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Use a meaningful population, mutation and selection balance, a stable stopping rule, and repeated seeded experiments to distinguish convergence from luck.<\/p>\n<p><script type=\"application\/ld+json\">{\"@context\":\"https:\/\/schema.org\",\"@type\":\"FAQPage\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"What is a genetic algorithm?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"It is a population-based search method that evaluates candidate solutions, selects promising candidates, and creates new candidates through variation.\"}},{\"@type\":\"Question\",\"name\":\"What is a fitness function?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"The fitness function scores how well a candidate meets the optimization objective; its direction and scale must be defined clearly.\"}},{\"@type\":\"Question\",\"name\":\"What do crossover and mutation do?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Crossover combines parts of parent candidates, while mutation introduces random changes that maintain exploration.\"}},{\"@type\":\"Question\",\"name\":\"How do I avoid a genetic algorithm stopping too early?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Use a meaningful population, mutation and selection balance, a stable stopping rule, and repeated seeded experiments to distinguish convergence from luck.\"}}]}<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.<\/p>\n","protected":false},"author":35,"featured_media":33554,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[1654],"tags":[5699,5695,5698,5696,5697],"class_list":["post-25715","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","tag-python-genetic-algorithm-ai","tag-python-genetic-algorithm-example","tag-python-genetic-algorithm-from-scratch","tag-python-genetic-algorithm-libraries","tag-python-genetic-algorithm-scipy","infinite-scroll-item"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.1 (Yoast SEO v28.0) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Genetic Algorithm in Python: Fitness, Selection, and Mutation<\/title>\n<meta name=\"description\" content=\"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Genetic Algorithm in Python: Fitness, Selection, and Mutation\" \/>\n<meta property=\"og:description\" content=\"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-26T07:23:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-07-13T07:12:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-b103.png\" \/>\n<meta name=\"author\" content=\"Rahul Kumar Yadav\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:title\" content=\"Python Pool\" \/>\n<meta name=\"twitter:description\" content=\"Practical Python tutorials, error fixes, code examples, and project guides.\" \/>\n<meta name=\"twitter:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-b103.png\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:site\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rahul Kumar Yadav\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/\"},\"author\":{\"name\":\"Rahul Kumar Yadav\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/person\\\/6553d7bda66441b1f50d0fda3f973d11\"},\"headline\":\"Genetic Algorithm in Python: Fitness, Selection, and Mutation\",\"datePublished\":\"2023-02-26T07:23:34+00:00\",\"dateModified\":\"2026-07-13T07:12:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/\"},\"wordCount\":1144,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-genetic-algorithm-guide-pythonpool.png\",\"keywords\":[\"python genetic algorithm ai\",\"python genetic algorithm example\",\"python genetic algorithm from scratch\",\"python genetic algorithm libraries\",\"python genetic algorithm scipy\"],\"articleSection\":[\"Algorithm\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/\",\"name\":\"Genetic Algorithm in Python: Fitness, Selection, and Mutation\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-genetic-algorithm-guide-pythonpool.png\",\"datePublished\":\"2023-02-26T07:23:34+00:00\",\"dateModified\":\"2026-07-13T07:12:31+00:00\",\"description\":\"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-genetic-algorithm-guide-pythonpool.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2026\\\/07\\\/python-genetic-algorithm-guide-pythonpool.png\",\"width\":1350,\"height\":650,\"caption\":\"Python genetic algorithm guide with selection crossover and mutation\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/python-genetic-algorithm\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.pythonpool.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Genetic Algorithm in Python: Fitness, Selection, and Mutation\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#website\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/\",\"name\":\"Python Pool\",\"description\":\"Practical Python tutorials, error fixes, code examples, and project guides.\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.pythonpool.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#organization\",\"name\":\"Python Pool\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2020\\\/08\\\/aa.png\",\"contentUrl\":\"https:\\\/\\\/www.pythonpool.com\\\/wp-content\\\/uploads\\\/2020\\\/08\\\/aa.png\",\"width\":452,\"height\":185,\"caption\":\"Python Pool\"},\"image\":{\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/x.com\\\/pythonpool\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/pythonpool\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.pythonpool.com\\\/#\\\/schema\\\/person\\\/6553d7bda66441b1f50d0fda3f973d11\",\"name\":\"Rahul Kumar Yadav\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g\",\"caption\":\"Rahul Kumar Yadav\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Genetic Algorithm in Python: Fitness, Selection, and Mutation","description":"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/","og_locale":"en_US","og_type":"article","og_title":"Genetic Algorithm in Python: Fitness, Selection, and Mutation","og_description":"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.","og_url":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/","og_site_name":"Python Pool","article_published_time":"2023-02-26T07:23:34+00:00","article_modified_time":"2026-07-13T07:12:31+00:00","og_image":[{"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-b103.png","type":"","width":"","height":""}],"author":"Rahul Kumar Yadav","twitter_card":"summary_large_image","twitter_title":"Python Pool","twitter_description":"Practical Python tutorials, error fixes, code examples, and project guides.","twitter_image":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-b103.png","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Rahul Kumar Yadav","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/"},"author":{"name":"Rahul Kumar Yadav","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/6553d7bda66441b1f50d0fda3f973d11"},"headline":"Genetic Algorithm in Python: Fitness, Selection, and Mutation","datePublished":"2023-02-26T07:23:34+00:00","dateModified":"2026-07-13T07:12:31+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/"},"wordCount":1144,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-guide-pythonpool.png","keywords":["python genetic algorithm ai","python genetic algorithm example","python genetic algorithm from scratch","python genetic algorithm libraries","python genetic algorithm scipy"],"articleSection":["Algorithm"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/","url":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/","name":"Genetic Algorithm in Python: Fitness, Selection, and Mutation","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-guide-pythonpool.png","datePublished":"2023-02-26T07:23:34+00:00","dateModified":"2026-07-13T07:12:31+00:00","description":"Build a genetic algorithm in Python with populations, fitness scoring, selection, crossover, mutation, elitism, and reproducible stopping rules.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-genetic-algorithm\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-guide-pythonpool.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2026\/07\/python-genetic-algorithm-guide-pythonpool.png","width":1350,"height":650,"caption":"Python genetic algorithm guide with selection crossover and mutation"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-genetic-algorithm\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"Genetic Algorithm in Python: Fitness, Selection, and Mutation"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonpool.com\/#website","url":"https:\/\/www.pythonpool.com\/","name":"Python Pool","description":"Practical Python tutorials, error fixes, code examples, and project guides.","publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonpool.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonpool.com\/#organization","name":"Python Pool","url":"https:\/\/www.pythonpool.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","width":452,"height":185,"caption":"Python Pool"},"image":{"@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/pythonpool","https:\/\/www.youtube.com\/c\/pythonpool"]},{"@type":"Person","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/6553d7bda66441b1f50d0fda3f973d11","name":"Rahul Kumar Yadav","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/a08d0e06327448519f969f3709bf615417591f24052e3d301fe02f3d4b4aef7b?s=96&d=wavatar&r=g","caption":"Rahul Kumar Yadav"}}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/25715","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=25715"}],"version-history":[{"count":15,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/25715\/revisions"}],"predecessor-version":[{"id":41969,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/25715\/revisions\/41969"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/33554"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=25715"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=25715"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=25715"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}