Can anyone explain me this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 ??

7th Apr 2020, 3:20 AM
ayushman tiwari
ayushman tiwari - avatar
5 Answers
+ 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).
7th Apr 2020, 7:27 AM
visph
visph - avatar
+ 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.
7th Apr 2020, 3:44 AM
Tricker
+ 1
Both are different list To see print their id Print(id(y), id(z))
7th Apr 2020, 6:38 AM
Rohit Shastri
Rohit Shastri - avatar
0
Thank you so much everyone for the quick reply 😃
7th Apr 2020, 12:50 PM
ayushman tiwari
ayushman tiwari - avatar
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.
8th Apr 2020, 3:48 AM
Jonathan Alvarado
Jonathan Alvarado - avatar