Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
strange slicing with [:]
#1
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[:]?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Assign all of a, to all of a
Reply
#3
but it's not a new list?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
oh, i see now, says the blind one. it's putting new contents, which are identical, into the same old place.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020