+ 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]

12th May 2019, 2:27 PM
Prakhar
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.
12th May 2019, 5:15 PM
Lothar
Lothar - avatar
+ 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.
12th May 2019, 3:48 PM
Seb TheS
Seb TheS - avatar
+ 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.
13th May 2019, 2:39 PM
Thoq!
Thoq! - avatar
+ 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
13th May 2019, 8:02 PM
Smith Welder
Smith Welder - avatar
0
You are not comparing two values you are just comparing two id of two varibles.
12th May 2019, 11:06 PM
Werg Serium
Werg Serium - avatar
0
...
12th May 2019, 11:06 PM
Werg Serium
Werg Serium - avatar