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

Time:01-22

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?

CodePudding user response:

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

CodePudding user response:

sort() doesn't work because it doesn't return the array, it only changes the existing array.

This would work:

arr_slice = array[2:7]
arr_slice.sort() # Sorts arr_slice but returns None
array[2:7] = arr_slice
  •  Tags:  
  • Related