[TriLUG] OT-ish: Python array slicing question
Steve Litt via TriLUG
trilug at trilug.org
Mon Dec 12 17:32:36 EST 2022
Nathan Yinger via TriLUG said on Mon, 12 Dec 2022 12:58:47 -0500
>There is a difference: a[:] creates a copy.
>
>a = [1, 2, 3, 4, 5]
>b = a
>c = a[:]
>a[0] = 7
>print(b) # [7, 2, 3, 4, 5]
>print(c) # [1, 2, 3, 4, 5]
>
>~Nathan
Very, very nice! I've coded Python for 12 years and didn't know that. A
few questions:
Is it a deep copy? In other words, if the array is an array of arrays,
are all the sub-arrays copies too?
Is there a way to do the same thing for dicts?
What's the best way of making a copy of a string?
Thanks to you and the OP for teaching me something valuable.
SteveT
Steve Litt
Autumn 2022 featured book: Thriving in Tough Times
http://www.troubleshooters.com/bookstore/thrive.htm
More information about the TriLUG
mailing list