I'd like to sort a list and observe/visualize how Python's sorting algorithm Timsort is moving the elements around.
First attempt: A subclass of list
which prints itself after each change:
class List(list):
def __setitem__(self, index, value):
list.__setitem__(self, index, value)
print(self)
That works when I change elements myself, but during sort
... nothing:
>>> a = List([None] * 2)
>>> a[0] = 'S'
['S', None]
>>> a[1] = 'P'
['S', 'P']
>>> a.sort()
>>>
Second attempt: Print the list (in global variable a
) at each comparison of elements:
class Str(str):
def __lt__(self, other):
print(a)
return other > self
That does something, but the list is always... empty?
>>> a = list(map(Str, 'test'))
>>> a.sort()
[]
[]
[]
[]
[]
[]
>>>
Why do these attempts fail, and is there a way to observe what Timsort is doing?