Python Forum
strange slicing with [:] - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: strange slicing with [:] (/thread-21658.html)



strange slicing with [:] - Skaperen - Oct-08-2019

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[:]?


RE: strange slicing with [:] - Yoriz - Oct-08-2019

Assign all of a, to all of a


RE: strange slicing with [:] - Skaperen - Oct-09-2019

but it's not a new list?


RE: strange slicing with [:] - ichabod801 - Oct-09-2019

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.


RE: strange slicing with [:] - Skaperen - Oct-09-2019

oh, i see now, says the blind one. it's putting new contents, which are identical, into the same old place.