同一のリストはis
、同じリストを参照しない限り、比較しても同等ではありません。リストの値が同じだからといって、メモリ内の同じリストを参照しているとは限りません。
例えば、
>>> a = [1,2,3]
>>> id(a) # memory location list a references
161267628
>>> b = [1,2,3]
>>> id(b) # memory location list b references, a different memory location than list a
161276396
>>> a == b
True
>>> a is b
False
>>> c = a # by this method of assignment; c points to the same point that a does;
# hence changes to a and changes to c, will change both.
>>> id(c) # memory location that c references; this is the same as where a points.
161267628
>>> a is c
True
>>> c.append(4)
>>> print a
[1, 2, 3, 4]
>>> print b
[1, 2, 3]
>>> print c
[1, 2, 3, 4]
>>> d = a[:] # this just copies the values in a to d.
>>> id(d)
161277036
これは、それらが異なるメモリ位置を指していることに意味があります。なぜなら、変更せずに最初のリストを変更したい場合 (4
末尾に追加するなどa
)と、メモリ内の同じ位置を指しているb
場合は不可能だからです。a
b