-1

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)

 
1

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I would slightly prefer self.shuffled_list = list(values). Calling .copy() will copy any old thing that happens to have that method, and you won't establish the invariant that you always store a list (and might get confusing errors from random.shuffle). self.shuffled_list = list(values) means the caller can pass a tuple or some other arbitrary iterable, and you'll handle it all the same, by shallow-copying to a new list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.