Click here to Skip to main content
11,715,491 members (85,610 online)
Rate this: bad
Please Sign up or sign in to vote.
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
0 Sergey Alexandrovich Kryukov 683
1 Richard MacCutchan 280
2 Maciej Los 259
3 OriginalGriff 160
4 F-ES Sitecore 135
0 Sergey Alexandrovich Kryukov 1,003
1 Richard MacCutchan 430
2 CHill60 415
3 Maciej Los 399
4 OriginalGriff 385

Advertise | Privacy | Mobile
Web04 | 2.8.150901.1 | Last Updated 26 Apr 2013
Copyright © CodeProject, 1999-2015
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