There are two ways to tell if they are the same in python. == and is. The return values are all Booleans, but what's the difference? That is something I'm curious about.
Simply put, is is comparing both memory locations, while == is simply looking to see if they have the same value. That's all.
Let's take a look at the code (launch python3 in the terminal)
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True
I will explain. If you assign a list to a and a to b as well, you can see that they are quoting from the same memory location. Therefore, this is True with is. Then use the string operation [:] to duplicate the list. Then, the copy will be completed and it will be different in memory. Therefore, this is False. about it.
When you actually look at the id
>>> id(a)
4364243328
>>>
>>> id(b)
4364202696
That's right. Since it is False, it is natural that the id is different.
However, there are exceptions like the code below.
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a == b
True
>>>
>>> a = 1000
>>> b = 10**3
>>> a == b
True
>>> a is b
False
What does this mean? Although a and b are assigned numbers separately, the results are different between the top and bottom. Well I will explain. Python does different things for small integers such as 256 to improve performance. It seems that such special integers are stored in the same place with the same id. Then, in 256, it will be the same True regardless of whether you use is or ==, and not for large numbers such as 1000.
It was that. What do you think. If you have any suggestions, please do so.
See you again
Recommended Posts