+ 2
Can anyone explain me this?
Condition 1 :- y = [1] z = y print(y is z) Output - True Condition 2:- y= [1] z = [1] print (y is z) Output - False How ??
6 Respuestas
+ 3
in the first case z contains strictly the same object (a reference of a list is stored in y -- its location in memory -- and that reference us copied in z) so y is z == True, and if you update the content of one of them, the other will reflect the changes...
in the 2nd case y and z contains 2 different lists (even if they have identical content / items -- they are store at 2 different memory location), so y is z == False, and if you update the content of one of them, the other will remain unchanged.
However, in both cases, y == x.
This notion of reference is important, and is related with mutable types (such as list, dict). Imutable types (such as number, string, boolean, tuple) doesn't deal with this notion as they arr always stored "by value" (the variable contains the value itself, not the memory location of the value).
+ 1
Programming isn't maths.
Read (y is z) as: y is assigned to z.
In the 2nd case y is assigned to [1] and z is assigned to [1], since y is not assigned to z therefore output is false.
+ 1
Both are different list
To see print their id
Print(id(y), id(z))
0
Thank you so much everyone for the quick reply 😃
0
In python is evaluate reference instead the == operator tha evaluate values. Example
x = 2
y = 2
print(x == y)
#output True
But is we is the output will be False because the values are stored in different places in the memory. Sorry for my English I'm learning it.