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 trialRatan Singh
1,440 PointsCan 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
Treehouse Moderator 68,454 PointsGood 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!!
Ratan Singh
1,440 PointsThank you for helping me out Chris
Ratan Singh
1,440 PointsRatan Singh
1,440 PointsOkayy....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
Treehouse Moderator 68,454 PointsChris Freeman
Treehouse Moderator 68,454 PointsItβs related to the local
items
in the function, because thatβs what assignment to items is about.