Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API: why don't Python arrays have a sort method?

Tags:

python

sorting

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.

like image 690
Luciano Ramalho Avatar asked Jan 01 '26 02:01

Luciano Ramalho


1 Answers

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.

like image 108
Martijn Pieters Avatar answered Jan 02 '26 17:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!