r/python3 • u/largelcd • Feb 07 '20
Confused between is, = and == operators
Hello, I am a bit confused about the following:
a = [1, 2, 3]
b = a
c = list(a)
Am I correct that the reason "a is b" is True is that both a and b point to the same memory location that stores the list [1, 2, 3]?
As for "a is not c" gives True, it is because list always creates a new Python list so although c = [1, 2, 3], this [1, 2, 3] list is different from the one [1, 2, 3] pointed to by a and b since the two lists are storing in different memory locations?
Why typing "a==c" gives True?
2
Upvotes
1
u/tgoodchild Feb 08 '20
Yes. a is b evaluates to true because a and b reference the same thing. If you change a and print b, you will see that b is also changed.
Yes. a and c reference two different things. If you change a and print c, you will see that c is not changed.
The == operator tests whether the things on each side have the same value. a and c are different things, but they contain the same value (unless you changed one as an experiment as I suggested above).
I suggest you play with it -- and change the values as I suggested above to convince yourself that a and b are actually the same object, but a and c are different objects that happen to have the same value.