How a Copy of a list works?
Craig created a copy of the list to avoid mutating the list and presenting different output every time the function is called :
def display_wishlist(display_name, wishes): items = wishes.copy() print(display_name + ":") suggested_gift = items.pop(0) print("====>",suggested_gift,"<====") for item in items: print("* "+ item) print()
Now, what i do not get is shouldn't the copy of the list stored in 'item' behave in the same way and display the same problem. So if you pop(0) from 'items', it will mutate and have on less items, so when the function is called twice the result is different every time. I thought that copies of lists do not mutate so i tried the following in the Shell:
created a list: list_1 = [1,2,3,4] copied it : list_2 = list_1.copy() then performed pop() on the copy: list_2.pop() then printed list_2: print(list_2): it was one item less [1,2,3] So, How come it didn't change and when Craig used it?
Steven Parker170,249 Points
You're quite right. Your copy gets changed, but it isn't saved anywhere. And each time the function runs, it starts out by making a fresh copy of the unchanged list.
oh! the light bulb just went on. I think the answer is : Since the original list is the same, every time a the function is called it will create the a copy of the original which have not changed, therefore the output wont change. My question had an error in its logic.
Still, i hope i can get an answer from the experts here to confirm whether my reasoning is correct?