Python Introducing Lists Using Lists Mutability

Can anyone clear doubt reg copy() method

I really thought items=wishes would give same output as items=wishes.copy() but it didn't Why?

The real question is why is the original list changing even when we only use items after items=wishes... So, calling the function second time again assigns wishes to items, but i could see wishes(list) changes. Why is the original list changing ????? Godddddddddddddd!

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 56,951 Points

Good question! Two important concepts:

  • An assignment statement is really only adding the label from the left-side of the = to point at the object defined on the right-side.
  • When object passed to an function, it is only a reference to the object that is passed in.

So, when display_wishlist("video games", video_games) is called, the parameter wishes points at the same object that the label video_games points at. When items = wishes is executed, then the label items also points to this same object. If items or wishes is mutated (an item in the list is altered), then the original video_games is also altered because all of the labels items, wishes, and video_games all point to the same object.

When .copy() is used, a new object is created. So items = wishes.copy() creates a new object distinct from the object the label wishes points at, and then label items then points at this new object.

Post back if you have more questions. Good luck!!

Okayy....So, when each time the function is called; items = wishes.copy() creates a copy to items that is not related to items, wishes, and video_games?? That's why the output is not changing..Am i right?

Chris Freeman
Chris Freeman
Treehouse Moderator 56,951 Points

It’s related to the local items in the function, because that’s what assignment to items is about.

Thank you for helping me out Chris