I want to write a class "SomeClass" that stores a shuffled version of the list it is initialised with. However, the list is shuffled in exactly the same way for every instance of my class. Could you please tell me what I am doing wrong?
import random
class SomeClass:
def __init__(self, list):
self.shuffled_list =list
random.shuffle(self.shuffled_list)
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
A = SomeClass(list)
B = SomeClass(list)
# Why are both lists the same?
print(A.shuffled_list)
print('\n\n')
print(B.shuffled_list)
All instances of your class will share the same list object, you need to copy it. Also don't use list
as a variable name since you're shadowing the type
def __init__(self, values):
self.shuffled_list = values.copy()
random.shuffle(self.shuffled_list)