Using sort() vs. sorted() when sorting a slice of an array- why does sort() not work?

I have an input array = [1,3,8,5,22,18,20,15,7,6,5]

And I want to sort the numbers from 8 to 20 in the list inclusive of 8 and 20.

Why does the following not work:

array[2:7] = array[2:7].sort()     #TypeError: can only assign an iterable

while

array[2:7] = sorted(array[2:7]) 

works.

I understand conceptually that sort() sorts the input in-place, while sorted() creates a new list. But I couldn't get my head around how this is linked to the above.

Is it because sort() changes the indexing, and thus leading to the first instance not working? But this can't be, because the error is a TypeError where it must be an iterable?


Solution 1:

The difference is that sorted can be applied to any iterable, be it a list or an immutable tuple, a set or even a generator and will produce a list. On the other hand, sort is a method provided by some mutable and ordered containers, and will change in place its container.

What happens is that the slice returns a copy, that copy will be correctly sorted by the sort method, but the return value of the sort method is... None! So your code ends to:

array[2:7] = None

... and None is not an iterable...