I know about the sorted() built-in function. This is an API design question, not a how-to question. I am wondering why the list type has a .sort() method to sort its contents in-place, but other mutable sequence types like array.array and bytearray do not.
The sort codebase (used by both sorted() and list.sort() works exclusively with list object, and is geared towards sorting python objects; items that can implement custom special methods that dictate ordering.
As such, that code is not readily reusable for the array.array and bytearray types, which deal exclusively in homogenous C type data.
Instead, you'd need to implement a dedicated sorting method for these types, taking advantage of the fact you are basically dealing with basic C types here. And no one has done this yet, which is really the only reason these types have no dedicated .sort() methods.
The work-around is to use sorted() and re-cast as the original type:
a = array.array(a.typecode, sorted(a))
b = bytearray(sorted(b))
The numpy ndarray type does have a .sort() method; perhaps you should use that library instead if you need to do a lot of sorting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With