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 trialTod Chung
1,073 Pointswhat is the difference between list2=list1[:].sort() and list2=list1[:] list2.sort() ???
what is the difference between
list2=list1[:].sort()
and
list2=list1[:]
list2.sort()
Why isn't the former work?
2 Answers
Charles Lee
17,825 PointsI did a bit of research about list slicing. One notable quote I found in Python's docs: "Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default)."
# Can't sort on read-only data attributes
list2=list1[:].sort()
# Reassigning list2 to the result of the slice.
list2 = list1[:]
list2.sort()
For more information: https://docs.python.org/3.5/library/functions.html#slice
Avinash Pandit
6,623 Pointssort method on a list doesn't return any value. It directly modifies the indies on the list items. In short, you can't directly assign list2.sort() to list1 ::check it out using help(list.sort()) in python shell
Although i do agree the example shown here does not really need the slice. list2 = list1[:] would have the same effect as list2 = list1
Chris Freeman
Treehouse Moderator 68,457 PointsThe first paragraph is correct. The second paragraph is not correct, in that, list2 = list1
would not have the desired effect. After executing list2.sort()
both list1 and list2 would be sorted.
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsThis is correct but imprecise as to why. There isnβt any read-only attribute involved.
list1[:]
creates a new list, which has thesort()
method availablesort()
method, it operates on the newly created list, sorting it in place, then returningNone
list2
is set to the returnedNone