what does is ?

Duncan Booth duncan at rcp.co.uk
Thu Nov 28 08:58:47 EST 2002


Padraig Brady <Padraig at Linux.ie> wrote in news:3DE4B96D.1060808 at Linux.ie:

> Well why does the following happen on 2.2?
> Is Python being clever about merging variables?
> 
> s1="123"
> s2=s1[:]
> s1 is s2 #true?

Slicing a list that way makes a copy, but strings are immutable so the
slice operator doesn't bother copying it. Tuples work the same way as
strings here:

>>> t1 = 1, 2, 3
>>> t2 = t1[:]
>>> t1 is t2
1
>>> 

Without using id() or the is operator, you cannot tell whether or not
s1/t1 were copied, so it is a small but useful optimisation to not copy
it. Note that the same thing happens if you use copy:
>>> from copy import copy, deepcopy
>>> copy(t1) is t1
1
>>> deepcopy(t1) is t1
1

But if the tuple contains mutable objects then it can be copied:

>>> t3 = (1, [], 3)
>>> copy(t3) is t3
1
>>> deepcopy(t3) is t3
0

In general Python will merge some constant strings, and small integers.
Don't use 'is' if this matters to you.



More information about the Python-list mailing list