Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
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
Updated 13-Dec-18 2:36am

1 solution

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?[^]
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900