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


Messages In This Thread
strange slicing with [:] - by Skaperen - Oct-08-2019, 10:27 PM
RE: strange slicing with [:] - by Yoriz - Oct-08-2019, 10:47 PM
RE: strange slicing with [:] - by Skaperen - Oct-09-2019, 12:31 AM
RE: strange slicing with [:] - by ichabod801 - Oct-09-2019, 12:35 AM
RE: strange slicing with [:] - by Skaperen - Oct-09-2019, 03:44 AM

Forum Jump:

User Panel Messages

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