Python Forum

Full Version: strange slicing with [:]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
as i understand it, slicing with [:] yields a new copy of the sequence, or if assigned to, replace the entire sequence (for a mutable sequence). but i have seen an odd effect when using [:] for both the source and target. the effect is that nothing happens. if i do
a=[1,2,3]
b=a
a=a[:]
b.append(4)
print(a)
i would not see the 4 append to b. but if i do
a=[1,2,3]
b=a
a[:]=a[:]
b.append(4)
print(a)
i do get the 4 as if a retained a reference to the same list.
Output:
lt2a/forums /home/forums 55> cat t1 a=[1,2,3] b=a b=a[:] b.append(4) print(a) lt2a/forums /home/forums 56> cat t2 a=[1,2,3] b=a a[:]=a[:] b.append(4) print(a) lt2a/forums /home/forums 57> python3 t1 [1, 2, 3] lt2a/forums /home/forums 58> python3 t2 [1, 2, 3, 4] lt2a/forums /home/forums 59>
what's going on with a[:]=a[:]?
Assign all of a, to all of a
but it's not a new list?
No. In assigning to a[:], you are not assigning to a, you are assigning to a slice of a. So the reference which is a is still pointing to the same place, which is the same place b is pointing to.
oh, i see now, says the blind one. it's putting new contents, which are identical, into the same old place.