Why Equal Integers Behaves Differently To Equal Lists?
This question is more a curiosity than anything else. I've been reading the details of the implementation of the int object in Python (1 and 2) and, as far as I can see, a Python
Solution 1:
You are not modifying the original integer, you are creating a new one and assigning the variable to it, and so the id is different.
a = 5
b = a
b += 1 # created a new intprintid(a), id(b) # differentis the same as
a = 5
b = a
b = b + 1 # created a new intprintid(a), id(b) # differentThe list equivalent would not be to use append, but to use +:
a = [5]
b = a
b = b + [6] # created a new listprintid(a), id(b) # differentThe is no equivalent append for ints, since ints cannot be modified but lists can.
The only potentially confusing thing is
a = [5]
b = a
b += [1]
printid(a), id(b) # sameThe reason is that the += operator (unfortunately, IMO) modifies the original list, so b += [1] and b = b + [1] are not equivalent statements. (See Why does += behave unexpectedly on lists?)
Post a Comment for "Why Equal Integers Behaves Differently To Equal Lists?"