# Mixed order sort with helper function (Python)

A Python sort with a helper function to allow for mixed order sort like age descending and weight ascending.

``````''' sort_helper101.py
use a sort helper function to perform a complex sort
here sort first by age in reverse order (descending, highest age first)
then by same age weight (ascending, lowest weight first)
tested with Python27 and Python33  by  vegaseat  30oct2013
'''

def sort_helper(tup):
'''
helper function for sorting of a list of (name, age, weight) tuples
sort by looking at age tup first then weight tup
'''
return (-tup, tup)

# original list of (name, age, weight) tuples
q = [('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]

print('Original list of (name, age, weight) tuples:')
print(q)
print('-'*70)
print('List sorted by age (descending) and same age weight (ascending):')
print(sorted(q, key=sort_helper))

# or using lambda as an anonymous helper function
print(sorted(q, key=lambda tup: (-tup, tup)))

''' result ...
Original list of (name, age, weight) tuples:
[('Tom', 35, 244), ('Joe', 35, 150), ('All', 24, 175), ('Zoe', 35, 210)]
----------------------------------------------------------------------
List sorted by age (descending) and same age weight (ascending):
[('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
[('Joe', 35, 150), ('Zoe', 35, 210), ('Tom', 35, 244), ('All', 24, 175)]
'''``````