107MP 107MP - 3 months ago 5
Python Question

Getting value from list in Python

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()

Answer

Because you are not creating an instance of your class and you are directly referencing the class attribute x of the test class. You also have to declare your attributes as instance attributes, hence defining them inside __init__():

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:

    def __init__(self):
        self.x = None
        self.y = None

# Create 10000 instances of the test class
lista = [test() for _ in range(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)
Comments