0

I have read this link recently here and it raises a question. The author only said about this

x = 23
y = x

But what about this

x = 23
y = 23

Is it still right that both x and y refer to one value 23 ? the first “23” is the same as the second “23” ? If it is then why I try this

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

The result is

[1, 2, 3]

Why is that? because both a and b refer to value [1,2,3] and list is a mutable type. As the author said "if two names refer to the same value, and the value is mutated, then both names see the change" In my code, b changed, why a didn't

  • I think you're confusing with [this](https://stackoverflow.com/questions/1145722/simulating-pointers-in-python) behaviour – GalAbra Jun 22 '19 at 12:00
  • 1
    Integers are immutable, for a start. There's also a cache of integers so their `id` will compare equal for small numbers. I can't properly understand what part you're confused about. – roganjosh Jun 22 '19 at 12:00
  • @roganjosh yeah i khow intergers are immutable, but what about the list, why a didn't change – JuniorCoder Jun 22 '19 at 12:02
  • Why would `a` change? Just because `a` and `b` happen to be lists with the same values does not make them share an object – roganjosh Jun 22 '19 at 12:04

1 Answers1

1

Creating a brand new list twice does not create an aliasing situation. Creating any mutable type twice, from scratch, will not cause aliasing. Your a and b have the same contents, but they are two completely different lists.

The CPython reference interpreter will occasionally cache small/simple immutable types (small ints, the empty tuple and str, etc.) so you would find that anything initialized to 23 is initialized to the same 23, but that's an implementation detail that rarely matters in practice. Basically, as long as you don't assign to one name from an already existing object (and don't do the trickier stuff like sequence multiplication or mutable default arguments), aliasing doesn't occur in any dangerous sense.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks for your answer, but can you explain more, why it does not creat an aliasing situation since both refer to 1 mutable value – JuniorCoder Jun 22 '19 at 12:13
  • @JuniorCoder: They don't. Each time you type `[1, 2, 3]` it makes a *new* mutable value. `a = [1, 2, 3]` followed by `b = a` would make both names alias the same mutable value, but otherwise, *all* freshly typed literals are logically distinct (even if, as noted, some immutable literals are actually the same, as a performance optimization). – ShadowRanger Jun 22 '19 at 12:23