1

I am new at programming and I have a very basic question that I still don't understand.

As far as I understand, everything is an object in Python and variables just point to an object. If an object is changed, all variables that point to that object will show the change.

with a list it makes sense:

nums = [1,2,3]
a = nums
nums.append(4)
print(id(a))
print(id(nums))

Both a and nums point to the same object.

What I don't understand is why with numbers it's different?

nums = 1
a = nums
nums += 1
print(id(a))
print(id(nums))

How can we know which object works like lists and which works like numbers when considering variables assignment?

accdias
  • 5,160
  • 3
  • 19
  • 31
  • 3
    Mandatory link: https://nedbatchelder.com/text/names.html – quamrana Dec 03 '19 at 14:59
  • 2
    `int`s are immutable, `list`s are mutable. The easiest way to tell is if you have any single `=` in your line (i.e. `nums += 1`), you are *reassigning* the object to a new reference. In contrast, any method you operate on the object (`x.method`, i.e. `nums.append`) you are operating directly on the same reference of the mutable object. – r.ook Dec 03 '19 at 15:00
  • 1
    Take a look here: https://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages – 404pio Dec 03 '19 at 15:01
  • 1
    Another way to read it is `nums += 1` is essentially `nums = nums + 1`. You can understand why `nums` reference will be different at this point because it has been *reassigned*. This answer might help you a little: https://stackoverflow.com/a/37535916/9183344 – r.ook Dec 03 '19 at 15:01
  • 1
    @r.ook not sure how much that helps... given that the list version of nums will work with nums += [3] (and list version of a will still point to the same list as nums) (note that if you do nums = nums + [3], that does in fact reasign x) – Foon Dec 03 '19 at 16:02
  • 1
    @r.ook mutability and immutability are (almost) completely unrelated to this, and referring to these concepts here is hugely misleading. The only relevant distinction is whether we reassign a name or not. It’s entirely conceivable to have a mutable number class, and nevertheless observe the same behaviour. – Konrad Rudolph Dec 03 '19 at 16:15
  • 1
    @Foon good point, I forgot `list` also has a `+=` operator... – r.ook Dec 03 '19 at 16:59
  • 1
    @KonradRudolph correct, this has more to do with naming and reference than mutability... though I feel it's still important for OP to understand why reference changes between the two types of object. The naming only becomes a problem because of the immutability of the `int` in the second sample, so I'd feel it's still part of the issue to understand. – r.ook Dec 03 '19 at 17:01

0 Answers0