I think you got the names backwards. Copy inside the function print_value
with lst = lst[:]
def print_reference(lst):
temp = lst.pop()
print(temp)
def print_value(lst):
lst = lst[:]
temp = lst.pop()
print(temp)
lst = ['hello', 'goodbye', 'laters']
print_value(lst)
print("After Value", lst)
print_reference(lst)
print("After Reference", lst)
Output:
laters
After Value ['hello', 'goodbye', 'laters']
laters
After Reference ['hello', 'goodbye']
BTW, list
is not good variable name because it shadows the built in 'list`.
Important is to distinguish what happens a compile time and what at run time.
This is fixed once the functions is defined:
def print_value(lst):
Therefore, copying list
with [:]
doesn't make sense and you get a syntax error.
But everything inside the function is executed when the function is a called.
Therefore, this line inside the function:
lst = lst[:]
makes a new (shallow) copy of lst
every time the function is called. This copy lives only inside the function and will be garbage collected once the function is finished (returned).