Python Introducing Lists Using Lists Mutability

Debajyoti Kar
Debajyoti Kar
Front End Web Development Techdegree Student 2,244 Points

couldn't we have just equated the two variables instead of using .copy?

I understand the purpose might have been just to share the existence of such method. But instead of using

  • items = wishes.copy() could he not have just done
  • items = wishes

is there any specific case where using .copy method might be more advantageous over simply equating the two variable? Or it doesn't matter and either would work.

Philip Schultz
Philip Schultz
10,870 Points

Hey, Here is a link to a conversation I had the other day. Steven explained to me why we have to use .copy() and not the equal sign. Basically, if you use the equal sign you are just making another reference to the same list. You want to make a copy of the list to accomplish most things. Read the entire thread! https://teamtreehouse.com/community/cant-use-remove-to-remove-the-list-from-inside-of-messylist-why

1 Answer

Steven Parker
Steven Parker
176,806 Points

As Philip explained, a simple assignment causes the new variable to point to the same list. So if you then add another item to "wishes", when you examine "items" it will be there also! To make them independent requires a copy.

The other question Philip linked to has a discussion about equality vs. identity that you may also find helpful.

Steven Parker
Steven Parker
176,806 Points

I don't think I realized until now that it was you asking both questions!

Philip Schultz
Philip Schultz
10,870 Points

Yup it was me. You've helped me out a few times now......really appreciate your help.

Debajyoti Kar
Debajyoti Kar
Front End Web Development Techdegree Student 2,244 Points

thanks, Steven and Philip. It makes sense. Since I have learned C and C++ first, sometimes I get confused as I am learning Python. Thanks for clarifying you guys.

Steven Parker
Steven Parker
176,806 Points

I can relate. I was a C/C++ developer for many years before I learned Python. Wow, what a difference! :wink:

Philip Schultz
Philip Schultz
10,870 Points

I went from C to Java and now Python.... it is a little confusing. I'm currently reading this article that goes really in depth about the topic. It points out that you can think of identities in python like you did pointers in C++. Check it out, it is a good read. https://www.blog.pythonlibrary.org/2017/02/28/python-101-equality-vs-identity/