Python – Sorting/grouping odd and even numbers in odd and even segregated list

pythonsorting

I have a unsorted list of number with even and odd. I need to segregate odd and even numbers in sorted order.

For example:

List = [5,6,4,7,11,14,12,1,3]

Expected output :

[4,6,12,14,1,3,5,7,11]

My program to segregate the odd and even numbers.

L = [5,6,4,7,11,14,12,1,3]
def segregateEvenOdd(L):
    left,right = 0,len(L)-1
    while left < right:
        while (L[left]%2==0 and left < right):
            left += 1
        while (L[right]%2 == 1 and left < right):
            right -= 1
        if (left < right):
            L[left],L[right] = L[right],L[left]
            left += 1
            right = right-1

print segregateEvenOdd(L)

output : [12, 6, 4, 14, 11, 7, 5, 1, 3]

I am trying to sort the list using insertion sort, couldn't get right output. Any way to sort this easily

Best Answer

Using a "smart" key function for list.sort / sorted:

>>> list(sorted(lst, key=lambda x: [x % 2, x]))
[4, 6, 12, 14, 1, 3, 5, 7, 11]

maps even numbers to the value [0, n], and odd numbers to the value [1, n], so that even numbers come first according to natural ordering.