1

Using the is operator on strings that have the same value returns True, but using the is operator on lists that have the same elements returns False. Why?

a = 'banana'
b = 'banana'

c = ['b', 'a']
d = ['b', 'a']

print(a is b)
print(c is d)

If the is operator compares whether the operands refer to the same object, both of the print statements should return True. However, that is not the case for lists. Thus, it seems that the two lists don't refer to the same object. Is there a specific reason why?

WorldGov
  • 157
  • 6
  • "If the is operator compares whether the operands refer to the same object, both of the print statements should return True" - that's not what it means for two things to be the same object. – user2357112 Dec 28 '18 at 16:08
  • If you do a `id(c)` and `id(d)`, it is different. Because, those are 2 separate list instances. In case of string, both point to the same instance (`print(id(a))` `print(id(b))`). Read on string interning in python. Also, `is` does a identity comparison and `==` does a value comparison. If you do `print(c == d)`, it returns `True`. – shahkalpesh Dec 28 '18 at 16:13
  • this is because 'is' operator only compare the `identity` it doesn't iterate . – sahasrara62 Dec 28 '18 at 16:14
  • I understand that strings point to the separate instance and lists don't, which is why the `is` operator throws different results. I wanted to know why -- and the questions linked as duplicates do not address that question. User @reportgunner's answer address that bit though. – WorldGov Dec 28 '18 at 16:18

1 Answers1

1

I believe it's because lists are mutable (can be modified, e.g. by my_list.append() or my_list.pop()) while strings can't.

check this video

  • that is, there is no point in storing two exact same strings since they can't be modified, but there IS a point in storing two lists since you might want to modify one of them. –  Dec 28 '18 at 16:11
  • Your comment on the answer is exactly what I was looking for. It does make sense to initialize lists two different objects since they can be mutated. Thanks. – WorldGov Dec 28 '18 at 16:19