Last active
May 21, 2023 19:49
-
-
Save rongpenl/398d0b18023903eecc73961725ce1979 to your computer and use it in GitHub Desktop.
Copying a Python list is tricky
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
hollyandprosper.com | |
YouTube Channel: https://www.youtube.com/@hollyandprosper | |
Link to the original YouTube Short: | |
part 1: https://youtu.be/642mFCjpHxA | |
part 2: https://youtu.be/VFGaapH0gaQ | |
part 3: https://youtu.be/k0ekMw6u5wU | |
""" | |
# part 1 and 2 example | |
import copy | |
list_a = [["1", "2"], "3", "4"] | |
list_b = copy.deepcopy(list_a) | |
list_b[0].remove("1") | |
print(list_a) | |
print(id(list_a) == id(list_b)) | |
print(id(list_a[0]) == id(list_b[0])) | |
# part 3 example | |
import copy | |
class Node: | |
pass | |
list_a = [1, 2, "alpha", "beta", Node()] | |
list_b = copy.deepcopy(list_a) | |
for val_a, val_b in zip(list_a, list_b): | |
print(id(val_a), id(val_b)) | |
# 'alpha'[0] = 'A' | |
# An error will be thrown. | |
answer = 42 | |
print(id(answer)) | |
answer += 1 | |
print(id(answer)) | |
# += actually creates a new object, which is counter-intuitive. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment