Skip to content

Instantly share code, notes, and snippets.

@jaycody
Created November 13, 2017 01:40
Show Gist options
  • Save jaycody/798209eed283588d27ccb6c2d131bb20 to your computer and use it in GitHub Desktop.
Save jaycody/798209eed283588d27ccb6c2d131bb20 to your computer and use it in GitHub Desktop.
Sort and sorted with custom key via lambda
""" SORT options with lambda function key
Given a list of non-empty tuples, return a list sorted in increasing
order by the last element in each tuple.
e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
[(2, 2), (1, 3), (3, 4, 5), (1, 7)]
"""
data = [(1, 7), (1, 3), (3, 4, 5), (2, 2)]
sorted_by_last = sorted(data, key=lambda tup: tup[::-1])
#OR
data.sort(key=lambda tup: tup[::-1]) # sorts in place
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment