Click here to Skip to main content
13,004,215 members (76,029 online)
Rate this:
Please Sign up or sign in to vote.
See more:
code part1:


code part2:


If I run the following code:

print name1 is name2

I get "True" for code part1
I get "False" for code part2

why? why the "reference" is same for name1 and name2 in "code part 1" and different for name1 and name2 in "code part 2"
Posted 26-Apr-13 0:16am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

This has to do with how Python stores strings internally. Two string literals that have the same content are stored as the same string instance1. Since strings are immutable this is OK to do so. The first sample uses strings so both the strings created from the same string literals are both pointing to the same string instance. The second example is with arrays. Since arrays are mutable a new instance is created for each array literal and that is the reason why the Is operator will return false in the latter case while true in the former.


— Manfred

1This is not true for strings that are constructed to have the same content. See this SO entry here: Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170627.1 | Last Updated 26 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100