0

My question is best explained with an example:

a = 1
b = a
a = a + 1

print(a,b)
# result is:  2  1


a = [1,2]
b = a
a.append(3)

print(a,b)
# result is:  [1, 2, 3]  [1, 2, 3]

I'm trying to understand the logic or at least the rule behind this behavior.

Why are a and b linked when the original object is a list(), but not when it is a int? And in general, what are the types of objects that are linked/ not linked? Is there a general rule?

Rob
  • 472
  • 4
  • 17
  • the short answer is thats just how it works. the longer answer involves talking about how different data types are represented in memory and optimization and ambiguity and stuff – SuperStew Oct 16 '19 at 15:28
  • Might be of relevance: https://stackoverflow.com/questions/56667280/if-two-variables-point-to-the-same-object-why-doesnt-reassigning-one-variable – MisterMiyagi Oct 16 '19 at 15:31
  • Plain assignment always "links" (i.e. refers to the same object). The difference occurs with the operations. I.e. `+` on `int` creates a fresh `int` (this cannot be said in general for all possible types), while `append()` keeps the list you passed and doesn't create a new list. – blubberdiblub Oct 16 '19 at 15:33

0 Answers0