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 Python Collections (2016, retired 2019) Slices Introduction To Slices

Sohail Mirza
seal-mask
.a{fill-rule:evenodd;}techdegree
Sohail Mirza
Python Web Development Techdegree Student 5,158 Points

using [:]

Sorry my question is very weird. In this video towards the end Kenneth use the following code clean_list = messy_list[:] , my question is why wouldnt the following line work clean_list = messy_list , all i am doing is removing is [:]

I understand kenneth said it copy all contents but again why wouldnt it work just by omitting [:]

why wouldnt this work

1 Answer

Steven Parker
Steven Parker
231,269 Points

When you make an assignment using a list, the assigned variable becomes a reference to the same list. If you want a copy of the list instead, you must make one with an operation like a slice or using the ".copy()" method.

If you make any changes to the original list, the difference between a reference and a copy will become significant. For example:

test = [1, 2]
test_ref = test
test_cpy = test[:]
test[0] = 99
print(test_ref[0])  # will show "99"
print(test_cpy[0])  # will show "1"