I am relatively new to Python, and I find the following difference between numbers and lists in classes confusing. See the code below.
The class MyClass
has a number some_number
and a list some_list
. When creating the instance myObject = MyClass()
as well as the number N = myObject.some_number
and the list L = myObject.some_list
, I can change the number N
without affecting myObject.some_number
as expected, but I cannot change the list L
without affecting myObject.some_list
. Therefore, I have two questions:
1) how should I instead approach to change L
without changing myObject.some_list
2) can anybody explain, why the logic is different for lists?
Thanks
class MyClass:
def __init__(self):
self.some_number = 100
self.some_list = [1, 2, 3]
myObject = MyClass()
N = myObject.some_number
L = myObject.some_list
# I can change the number N without affecting myObject
N = 90
print(N) # Output: 90
print(myObject.some_number) # Output: 100
# I cannot change the list L without affecting myObject
L[0]=9
print(L) # Output: [9, 2, 3]
print(myObject.some_list) # Output: [9, 2, 3]