0

Another a, b = b, a question?

a, b = [0], [0] a, b = b, a If(a is b): print(True) else: print(False) Output: False I posted a question similar to this a few weeks ago and people kindly pointed out that a, b = b, a was not Boolean logic, but just an equation. And that a, b = b, a was Python's way of switching values. So since all values are zero, and 0 = 0, why is the answer false?

13th Apr 2019, 10:20 PM
tristach605
tristach605 - avatar
3 Answers
+ 10
Two misconceptions. 1.) The values are not zero, they are a list with a zero in it. 2.) 'is' doesn't check for equality, it checks for identity. Two twins may be equal, but they are still two separate kids, not one. In your computer's memory there are two lists with a zero in it - two separate lists in different places. So '==' would be True, but 'is' is False. 'Hey, I saw a guy down at the market the other day that looked like you, like exactly like you, man!' 'No, no, that was really me, I was down at the market that day!' In this case, 'is' would be True.
13th Apr 2019, 10:52 PM
HonFu
HonFu - avatar
+ 10
# We create 2 lists <a> and <b>, both has 1 item, a value of zero. Even though the 2 lists contain similar value they are two different objects. a, b = [0], [0] # We swap the object reference. <a> now refers to object pointed to by <b>, vice versa a, b = b, a # Since the "is" operator checks for reference, the condition evaluates to False. <a> and <b> are different objects after all. if(a is b): print(True) else: print(False) # Now we change <b> to refer to object pointed to by <a>. Having both <a> and <b> be referring to identical object, "is" operator yields True. b = a print(a is b) HonFu 👍 for excellent illustration.
13th Apr 2019, 11:06 PM
Ipang
+ 2
Thanks Ipang and HonFu! Clearer now. I'll keep studying.
14th Apr 2019, 1:35 AM
tristach605
tristach605 - avatar