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 trialSohail Mirza
Python Web Development Techdegree Student 5,158 Pointsusing [:]
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
231,269 PointsWhen 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"
Sohail Mirza
Python Web Development Techdegree Student 5,158 PointsSohail Mirza
Python Web Development Techdegree Student 5,158 PointsHi Steven
Thanks for the info... that was exactly what the answer i was looking for