Friday, July 1, 2022

Python - Copy lists

list1 = ["apple", "banana", "cherry"]
list2 = list1
# Right now these are identical
print (list1)
print (list2)

list1.append('orange')

# Notice that the new item is also added to list2
# ['apple', 'banana', 'cherry', 'orange']
print (list1)
print (list2)

# I think this means list2 is a pointer referencing list1.
# So changes made to list1 are seen in list2,
# and vice-versa.

list2.pop()
# ['apple', 'banana', 'cherry']
print (list1)
print (list2)

# So we need a way to actually *copy* the list
list2 = list1.copy()

list1.append('orange')
list2.pop()

# Now we're cooking with gas
# ['apple', 'banana', 'cherry', 'orange']
# ['apple', 'banana']
print (list1)
print (list2)

print("---")
# Another way to copy a list
list1 = ["apple", "banana", "cherry"]
list3 = list(list1)

# ['apple', 'banana', 'cherry']
print (list3)
list3.insert(2, "popsicle")

#['apple', 'banana', 'cherry']
#['apple', 'banana', 'popsicle', 'cherry']
print (list1)
print (list3)