title: Plot the fitness of a genetic algorith. How to access object values inside a function
body: <p>I have a genetic algorithm that is designed for dicovering a string with 7 letters, with 20 individuals in each population and 600 generations.</p>
  <p>I want to create a plot that graphs the mean of the fitness for each generation</p>
  <p>The first thing I decided to do is to create a list that stores the mean for each generation, so then I can plot it later.</p>
  <pre><code>def initialize_population():
      population = []
      for i in range(0, GENES):
          adn = [random.choice(string.printable[:-5]) for _ in range(0, len(desired_string))]
          fitness = obtain_fitness(dna, desired_string)
          candidate = Individual(dna, fitness)
          population.append(candidate)
      return poblacion
  </code></pre>
  <p>This function above calls for different functions, to obtain fitness value, etc, and creates a population (list) of candidates, each with a dna (string) and a fitness. This function above is inside another function called simulation, which executes the script.</p>
  <p>What I want is to get the fitness value for each candidate, but I didn´t manage to do that.</p>
  <pre><code>progress = []
  for i in range(0, MAX_GENERATION):
      progress.append(numpy.mean(sum(candidate.fitness[i])))
  </code></pre>
  <p>But this gives me the error:</p>
  <pre><code>NameError: name 'candidate' is not defined
  </code></pre>
  <p>As you can see, <code>candidate</code> was defined in the initialize_population function, but I don´t know how to call it.</p>