Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Use of "is" in python

Here is the code-

a="Done"
b="Done"
c=input("Enter Done :")      #c takes the value "Done"
print(a is b)
print(a is c)

The first print statement prints True, whereas the second one prints False. Why is that happening?

1 Answer

Steven Parker
Steven Parker
216,136 Points

The is operator is an identity test, unlike == which is an equality test. Your string literal referenced by both variables a and b (because Python optimized them to one object) is stored separately from the input string referenced by c. That's why "a is b" but not "a is c".

However, if you tried "a == c" you would find that to be True.

Are there any particular names for the places where literals and the input strings are stored?

Chris Freeman
Chris Freeman
Treehouse Moderator 67,989 Points

The area where all objects are stored is call the "heap" (see docs). Variables names are stored in a namespace.

The namespace dictionary holds the name of the variable as the "keys" and the address of the object's location in the heap as the "value".

When an object is created (the right-side of the equals sign) if it is an immutable (unchangable) object then the heap of objects is checked to see if it is already present. This happens for strings and small numbers. If present, the variable name is pointed to the preexisting object.

The id() of an object is it's address in memory or "value" in the namespace dict. So if the id of two variables match, the object they reference is the same object in the heap.

Python 3.3.0 (default, Nov 26 2015, 16:04:52) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on unknown
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'DONE'
>>> b = 'DONE'
# checking the id of the literal
>>> id('DONE')
110178112
# matches variables pointing at the same literal
>>> id(a)
110178112
>>> id(b)
110178112
# input() creates a new object 
>>> c = input("> ")
> DONE
>>> c
'DONE'
>>> id(c)
110177920

>>> a == c
True
>>> a is c
False

Thanks!