+ 2

What is difference between 'is' and '==' in python ?

a = [1,2,3] b = [1,2,3] print (a is b) # false print (a == b) # true I'm puzzled by these outputs.

31st May 2018, 1:58 AM
ankush_953
4 Answers
+ 5
https://code.sololearn.com/cARyHC62Rq0E/?ref=app Hopefully this code can help you understand. Variable equality and list equality are a little different in Python. Variables are stored by value and lists are stored by reference. The equality operator (==) compares variables and lists alike by value. Since a and b have the same values, a == b. The is keyword is a little different. It checks if a list is an alias to the same list. The alias variable (in my code it is list c) has the same values as the original list yes (a list) but c was assigned with c or really the reference to the a list making c an alias to a. Basically, c IS another name for a in my code, but b is separate from a even if it has the same values making b IS NOT c.
31st May 2018, 2:59 AM
Maxwell Anderson
Maxwell Anderson - avatar
+ 3
"==" returns true if 2 quantities are equal in value. "is" returns true if 2 quantities have the same value, and originate from the same source. for mutable objects, "==" can return true but "is" may return false. for immutable objects, both are essentially the same
31st May 2018, 4:41 AM
👑 Prometheus 🇾🇬
👑 Prometheus 🇾🇬 - avatar
+ 2
You will find your answer here Refer the 6th point: https://www.sololearn.com/discuss/1187881/?ref=app
31st May 2018, 12:53 PM
Mitali
Mitali - avatar
0
but there are many things like this in python so how can I manage to remember all this ?
31st May 2018, 5:57 AM
ankush_953