+ 2
Please can someone explain why the answer is 0 ?
a = [2, 3] b = [2, 6] a[1] *= 3 b[1] += 3 print(int(a is b))
6 ответов
+ 10
Python „is“ keyword is used to check if the memory reference of two Python objects are same or not.
In the above example, the contents of a and b are same, but a and b are different objects having a different memory allocation.
That returned int(False) = 0
+ 4
If id(a) == id(b) then ( a is b) returns true. Otherwise returns false.
+ 3
a = [2, 3]
b = [2, 6]
a[1] *= 3 # a becomes [2, 9]
b[1] += 3 # b becomes [2, 9]
Although both a and b represent [2, 9], they are pointing to different reference.
To check the reference, we can use id() function.
If you run below code:
print(id(a))
print(id(b))
The output will not be the same.
When we create 2 lists, they are pointing to difference reference.
If you reassign one equal to another, then both will point to the same reference.
x = [1, 2]
y = [1, 2] # x and y have different id
y = x # now y’s id is the same as x’s id
Since a and b are pointing to different ids, running int(a is b) return False. And integer of False is 0, so it prints 0.
+ 2
Thanks so much for the help.
+ 1
In python developer course, how we complete the code in Classes (the video game problem)?
0
Becaus int(False) = 0