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 Python Basics Types and Branching Comparisons

Patrick Poplawska
Patrick Poplawska
8,814 Points

"is" operator is returning True unexpectedly

Interesting behavior (in REPL): favorite_color = 'red' favorite_color is 'red' returns True.

Is this because Python is doing some clever object management in the background, and not creating a new string object containing the value 'red' when I execute the branch expression?

1 Answer

Patrick Poplawska
Patrick Poplawska
8,814 Points

Did a quick search, and by using the id() function I am able to confirm that (even when assigning to another variable) that this behavior is happening because it points to the same address in memory. The variable portion is a consequence of strings being immutable.