Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.

You have just discovered that a slice was not a true container…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading