Skip to content Skip to sidebar Skip to footer

List Appears To Be Empty During Sorting

I wanted to sort a list in-place and tried using the list itself during the sorting (within a key function). I found out that the list itself appears to be empty in there. a = [1,

Solution 1:

From the listobject.c source code:

/* The list is temporarily made empty, so that mutations performed
 * by comparison functions can't affect the slice of memory we're
 * sorting (allowing mutations during sorting is a core-dump
 * factory, since ob_item may change).
 */

and from the Mutable Sequence Types documentation:

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python 2.3 and newer makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

You could zip a and b instead:

b[:] = [bval for(aval, bval) in sorted(zip(a, b))]

Post a Comment for "List Appears To Be Empty During Sorting"