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

Why don't just use clean_list = messy_list ?

why don't we just use clean_list = messy_list instead of clean_list = messy_list[:]

1 Answer

Hi,

using clean_list = messy_list does not actually create a copy of messy_list. Instead, it causes clean_list to reference to the same object as messy_list, meaning that if you change one of them, the other will change too. Sometimes an independent copy needs to be made, that's why clean_list = messy_list[:] is used.

Thanks a lot. At first, I thought when I use A = B it would put the value of B into A And when I change A, it won't affect B.

However, it seems I misunderstood the concept.

I guess it's because Python is an object-oriented language? Or does this situation works with all language?

Actually, both cases are true, it depends on whether the object you copy is immutable or mutable. What you say is correct e.g. for strings, as they are immutable, but lists are mutable objects. So copies of strings can be made simply with a = b, but the same won't work for lists.

Wow! Again, thanks a lot. You really clear things up.