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 (Retired) Slices Introduction To Slices

Tod Chung
Tod Chung
1,073 Points

what 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

I 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

Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

This is correct but imprecise as to why. There isn’t any read-only attribute involved.

  • list1[:] creates a new list, which has the sort() method available
  • using the sort() method, it operates on the newly created list, sorting it in place, then returning None
  • list2 is set to the returned None
Avinash Pandit
Avinash Pandit
6,623 Points

sort 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
Chris Freeman
Treehouse Moderator 68,457 Points

The 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.