b = a vs b = a[:] in strings|lists
in Lists
-
I can always check that b=a
points to same object and c=a[:]
creates another copy.
>>> a = [1,2,3,4,5]
>>> b = a
>&g开发者_如何学JAVAt;> c = a[:]
>>> a[0] = 10
>>> b
[10, 2, 3, 4, 5]
>>> c
[1, 2, 3, 4, 5]
In Strings
-
I cannot make a change to the original immutable string. How do I confirm myself that b=a
makes b
point to same object, while c = a[:]
creates a new copy of the string?
you can use the is
operator.
a = 'aaaaa'
b = 'bbbbb'
print a is b
a = b
print a is b
c = a[:]
print c is a
This works because a is b
if and only if id(a) == id(b)
. In CPython at least, id(foo)
is just the memory address at which foo
is stored. Hence if foo is bar
, then foo and bar are literally the same object. It's interesting to note that
a = 'aaaaa'
b = 'aaaaa'
a is b
is True
. This is because python interns (at least most) strings so that it doesn't waste memory storing the same string twice and more importantly can compare strings by comparing fixed length pointers in the C implementation instead of comparing the strings byte by byte.
It's still possible to have the same string stored in more than one place - see this example.
>>> a="aaaaa"
>>> b=a[:]
>>> b is a
True
>>> b=a[:-1]+a[-1]
>>> b is a
False
>>> b==a
True
>>>
精彩评论