I'm writing a simple script in Python, that creates a list of 10000 instances of test class. Then I'm looping through every element in the list and changing value of variable x to random string generated using id_generator method.
import string
import random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class test:
x = None
y = None
d = test
lista = [d] * 10000
w = 0
while (w < 10000):
lista[w].x = id_generator()
w = w + 1
print(lista[3].x)
print(lista[40].x)
print(lista[1999].x)
Why do I get 3 same values on the output? Shouldn't I get 3 different values generated using id_generator()
lista = [test() for _ in xrange(10000)]. While loop is ugly too, replace it with for in...lista[1] is lista[1493]returnsTrue. That is because you create only a single object that is 10000 times in your list.d = test; lista = [d] * 10000is supposed to do.print(lista[w].x)inside the loop gives me 10000 different strings.