# partial list sort

Eddie Corns eddie at holyrood.ed.ac.uk
Wed Oct 9 14:48:41 CEST 2002

```jsaul <jsaul at gmx.de> writes:

>Hi there,

>I am looking for the proper way to sort a list range-wise. The
>scenario is as follows: I am reading a list of data elements
>triple-wise component A, B and C, then the next triple A, B, C and
>so on.  Each list element has a component identifier which takes
>the values "A", "B", or "C". What I want is to sort the components
>within each *triple*, but *not* the while list, so that I can
>assure an order of A-B-C no matter what the original order in the
>data was, which can as well be B-C-A or whatever.

>Here is a simplified version of my script illustrating the
>problem:

>    list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ]
>    print list

>    def sort_components (list):
>	def cmp_comp (data1, data2):
>	    if   data1[1] == data2[1]:  return  0
>            elif data1[1]  < data2[1]:  return -1
>	    return 1
>        print list
>	list.sort(cmp_comp)
>        print list
>	return

>    for k in range(0, len(list), 3):
>	# sort over ranges:
>        sort_components(list[k:k+3])

>    print list

>The resulting output is:

>    [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']]
>    [[1, 'C'], [2, 'B'], [3, 'A']]
>    [[3, 'A'], [2, 'B'], [1, 'C']]
>    [[4, 'C'], [5, 'B'], [6, 'A']]
>    [[6, 'A'], [5, 'B'], [4, 'C']]
>    [[1, 'C'], [2, 'B'], [3, 'A'], [4, 'C'], [5, 'B'], [6, 'A']]

>What I want is

>    [[3, 'A'], [2, 'B'], [1, 'C'], [6, 'A'], [5, 'B'], [4, 'C']]

>You see that *within* the function 'sort_components' each triple
>is sorted properly, but after leaving that function, the sorting
>is not retained. I want to sort the list triple-wise preferably
>*without* restructuring the list.

>Can anybody give me a hint about what I have overlooked?

Hint: list[x:y] is a COPY of the elements ie a new list.

Solution: eg sort_components returns list and 'for loop' appends (using
extend!) these to a list was initially empty.  Use newly created list instead
of original.

Eddie

```