Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Using Lists Mutability

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?

3 Answers

Steven Parker
Steven Parker
231,268 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?

This explanation solidified my suspicion after mentally following the code and process through. But, I wasn't entirely sure until I read aa114's rationalization and Steven's confirmation. I think the instructor could have clarified that during his delivery to eliminate unnecessary doubts for the students.

Thanks to both of you.