0

I'm just starting to learn Python. I'm stuck upon a problem. Kindly clear my doubt.

a='abc'
b='abc'
a==b                 #When I run this O/P is True. But, in C/C++ or Java it turns out to be False because the variables(a & b) refer to different memories.

a is b               #When I run this O/P is True. Ok understood , but.....

BUT WHEN

a=[1,2,3]
b=[1,2,3]
a==b                #The out put is True

a is b              #THe output is False

What is the reason for the two different outputs in the case of strings and lists?

IcyFlame
  • 5,059
  • 21
  • 50
  • 74
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • 2
    Small strings and integers are *interned*; cached and only one object is created for the lifetime of the interpreter. `is` tests identity (same object), so `a` and `b` are the *same object*. The lists are two separate objects that happen to represent the same value (equal). – Martijn Pieters Jun 18 '13 at 14:15
  • See: http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers and http://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why and http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python – Jon Clements Jun 18 '13 at 14:15
  • Actually, a direct translation of your first snippet to C (`const char *a = "abc"; ... a == b`) or Java (`String a = "abc"; ... a == b`) yields true, because string literals are interned there too. –  Jun 18 '13 at 14:18
  • @delnan- Thanks for pointing that out. But I was talking wen I compare 2 chars...for eg= char a[4]='abc' and char b[4]='abc' and then comparing them yields False. – Praful Bagai Jun 18 '13 at 14:24
  • My question actually is Why a is b in case of list is False but in case of strings it's True. Why – Praful Bagai Jun 18 '13 at 14:25
  • @MartijnPieters-- +1 for your answer.
    I tried it for A=1 and B=1. then A is B yields True. and for A=257 , B=257 yields False. Thanks
    – Praful Bagai Jun 18 '13 at 14:32

0 Answers0