Newbie: Classes and Lists

CGH chooper at umich.edu
Tue Apr 2 22:29:09 EST 2002


Hi,

I am very new to Python and have a very simple question. I want to create
a 'chromosome' class for a genetic algorithm program. Essentially I just 
want a class that contains a list of n bits. That part seemed easy: here is 
what I tried:

==============================================================================

import random

class Chromosome:

    data = []
    
    def __init__(self, length):
        for bit in range(length):
            self.data.append(random.randrange(0,2,1))

    def display(self):
        print self.data


population = []

for i in range(100):
    x = Chromosome(20)
    population.append(x)

population[50].display()

===================================================================

I want to define a population of 100 chromosomes. But instead of a list of 
Chromosome objects I seem to get one big (100 x 20) list of 0s and 1s. 
Clearly I've misunderstood something fundamental here. Any help would be 
appreciated.

Cameron



More information about the Python-list mailing list