Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
code part1:
 
 
 name1="rahul"
 name2="rahul"
 
 

code part2:
 
 
name1=[1,2,3]
name2=[1,2,3]
 
 
If I run the following code:
 
print name1 is name2
 
I get "True" for code part1
and
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 1:16am

1 solution

Rate this: bad
good
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.
 
Regards,
 
— 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?[^]
  Permalink  
v2

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

  Print Answers RSS
0 OriginalGriff 295
1 DamithSL 265
2 CPallini 235
3 Maciej Los 190
4 George Jonsson 170
0 OriginalGriff 5,415
1 DamithSL 4,422
2 Maciej Los 3,820
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,911


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 26 Apr 2013
Copyright © CodeProject, 1999-2014
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