+ 1

When a=[1], a is not [1]??

a = [1] if a is [1]: print(True) else: print(False) -------- output: False I dont understand...

19th Aug 2017, 1:31 AM
ê°•ìŁŒí˜„
ê°•ìŁŒí˜„ - avatar
3 Answers
+ 3
is operator checks if the object is same or not . IT DOES NOT CHECK THE VALUE. '=='' OPERATOR CHECKS THE VALUE In a=2 type things a is 2 obviously because a is a int type variable assigned 2. But in a=[1,2] this type of things...the interpretation goes like a is pointing to the list U can not say a is the list cause variable type of a canot be a list. It can be float char string.. Thats why in f="abc" and g="abc" f is g .same reason for why it shows false in tuple and dictionaries HERE IS MOST OF THE PROBABABLE POSSIBILITIES I ENLISTED IN THE CODE... CHECK ALL OUTPUTS--> https://code.sololearn.com/cV29KjXuD9zv/?ref=app
19th Aug 2017, 2:57 AM
sayan chandra
sayan chandra - avatar
+ 7
'is' operator returns True if both objects are exactly same. It means, even if two objects have same contents, 'is' returns False when two variables point to different objects. Example a=[1,2] b=[1,2] c=a print(a is b) print(a is c) -----Output----- False True
19th Aug 2017, 2:22 AM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 3
Yes and no to what it's been previously said. The `is` operator checks for the identity of the comparing objects, that is, if two or more identifiers have the same id (i.e. the return value of the `id` standard function) they're considered the same object and thus the `is` operator will return true for those operands. However, your test case above has more to do with Python internals than it seems. When interpreting a script, along when starting and running up the interpreter, Python creates constants like `None`, booleans and integers up until a certain size, interns some small strings, etc. Unlike all of that, container literals like lists, dicts, sets, and whatnot are never interned (because, if you think about it, it doesn't make that much sense), so wherever we write these literals, they're most likely to be different objects. Furthermore, how Python interns basic objects is implementation specific, so identity checks on objects other than those meant to be constant can't be relied upon. Use value-comparison operators if equality checks is what's intended (and that's usually the case). If you feel like it, these answers at stackoverflow i.m.o. are two good places to start to know about how these Python internals behave, https://stackoverflow.com/a/16757434/7502658 https://stackoverflow.com/a/24245514/7502658
19th Aug 2017, 5:00 AM
Edgar Garrido
Edgar Garrido - avatar