0

if I typed

a = [1,2,3,4]
b = a
print(a is b)  # it will print true 

but if i typed

a = [1,2,3,4]
b = list(a)
print(a is b)  # it will print False

i can understand this because when i used list it actually returned another list and assigned it to b so both a and b are different lists now with different places in meomery

but when i use same same concept with strings its different

 a = 'kha'
 b = 'kha'
print( a is b) #it prints true

so why this happens both are supposed to be different variables with different values why same concept with lists doesn't work with strings arent string a and b both have different places in meomery they both both have same values but they different things

khaled
  • 69
  • 1
  • 7
  • 2
    `list` makes a new list, but the interpreter is free to [intern string literals](https://en.wikipedia.org/wiki/String_interning) if it wants. `a` and `b` are still separate variables that happen to point to the same string. Since Python strings are immutable, this is a valid optimization. – Cameron Apr 10 '20 at 17:27
  • This could also be in the duplicates list: https://stackoverflow.com/q/3647692/10077 – Fred Larson Apr 10 '20 at 17:28
  • Possible duplicate : https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator – Ch3steR Apr 10 '20 at 17:28
  • 1
    Immutable objects (such as strings) may be freely shared without consequences, and in fact it is preferable to do so. In the case of strings, Python will often share them when it recognizes they're the same. Just be happy when it does, since it's that much less memory it's using. – Tom Karzes Apr 10 '20 at 17:31
  • Here's another example: `set() is set()` is obviously `False` (it has to be), but `frozenset() is frozenset()` is `True`. And of course `[] is []` is `False`, but `() is ()` is `True`. – Tom Karzes Apr 10 '20 at 17:33

0 Answers0