+ 5
Can anyone explain me this challenge question...
I found this question in one of the python challenge. a = [2] b = [2] if a is b: print (a + b) else: print (b) The answer of this question is - [2]
7 Answers
+ 9
a and b can be compared this way:
[a] == [b] â> True, as both have the same value assigned.
[a] is [b] â> False, as swim already mentioned.
+ 5
It is weird that:
"123" is "123" -> True
["1", "2", "3"] is ["1", "2", "3"] -> False
I thought strings would work little similar to lists... and it is not about that strings are immutable, because tuples gave the same result as lists.
+ 5
@Seb TheS
In Python strings are handled differently for performance reasons. Python assumes that it is very likely that strings get used more than once and thus keeps them around even if they are not referenced to anymore. Initiating strings is pretty slow. The same applies for Java.
+ 2
Because "a" it's list, "b" it's another list.
2 is the value in the list
print(a[0]) # get value on index
if a is b: #False
........
else: print (b) #[2]
These are different objects(lists)
a = 2
b = 2 now it's the same objects
if a is b: #True
print(a+b) # 4
0
You are not comparing two values you are just comparing two id of two varibles.
0
...