Skip to content

Instantly share code, notes, and snippets.

@rameshbaskar
Created October 24, 2021 14:26
Show Gist options
  • Save rameshbaskar/0fc19896fe01b0942f1446c8d5a06f58 to your computer and use it in GitHub Desktop.
Save rameshbaskar/0fc19896fe01b0942f1446c8d5a06f58 to your computer and use it in GitHub Desktop.
Python - variable referencing and copy example
import copy
# Base list
list1 = ["apple", "banana", "cherry"]
print("By default Python creates variables by reference")
list2 = list1
print("Now while list2 and list1 seems like two variables they refer to the same memory reference")
print("So modifying one variable will modify the others")
print("To confirm this we will print the memory address for both the variables")
print("Memory address of list1: " + str(id(list1)))
print("Memory address of list2: " + str(id(list2)))
print("Now let\'s modify list1 and we will confirm that list2 is also affected and vice versa")
print("Adding an item to list1")
list1.append("orange")
print(list1)
print(list2)
print("Removing an item from list2")
list2.remove("orange")
print(list1)
print(list2)
print("Now let us try shallow copy where distinct memory addresses are created for each variable. For this we will use copy module.")
list2 = copy.copy(list1)
print("We will confirm this by printing the memory address of list1 and list2")
print("Memory address of list1: " + str(id(list1)))
print("Memory address of list2: " + str(id(list2)))
print("Now we will add an item to list1 and list2 will remain intact")
list1.append("orange")
print(list1)
print(list2)
print("Now we will remove an item from list2 and list1 will remain intact")
list2.remove("cherry")
print(list1)
print(list2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment