0

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]
Jasoba
  • 101
  • 1
  • 1
    You never change the number. `int` objects are immutable. They don't expose mutator methods. List objects do, like item assignment: `my_list[i] = x`, or `my_list.append`. `int` objects have nothing like that. You merely assign another, *new `int` object to the name `N`*. You could do the same with a list, `L = [1,2,3]` and you'll see the same behavior. You *do* change the list. Both the int and the list being referenced by the global `N` and `L` names *are the same objects inside your `MyClass` object*. I suggest reading the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Mar 09 '20 at 02:00
  • IOW, the logic is exactly the same for `list` objects and `int` objects. You were merely mistaken about what constitutes changing an object. Assignment *never changes an object* It changes a *what a name refers to* – juanpa.arrivillaga Mar 09 '20 at 02:00

0 Answers0