Skip to content

Instantly share code, notes, and snippets.

@suriyadeepan
Created August 29, 2016 06:33
Show Gist options
  • Save suriyadeepan/3f90ca38ed701baeead09b39e1c0475a to your computer and use it in GitHub Desktop.
Save suriyadeepan/3f90ca38ed701baeead09b39e1c0475a to your computer and use it in GitHub Desktop.
Sort a list based on more than one attribute
lst = [ 'file', 'if', 'hat', 'zoltan', 'calculator', 'cup', 'pocket', 'symbolic', 'I', 'attributes' ]
sorted_lst1 = sorted(lst, key=len)
print(sorted_lst1)
## OUTPUT : ['I', 'if', 'hat', 'cup', 'file', 'zoltan', 'pocket', 'symbolic', 'calculator', 'attributes']
sorted_lst2 = sorted(lst, key=lambda item : (len(item),item[0]) )
print(sorted_lst2)
## OUTPUT : ['I', 'if', 'cup', 'hat', 'file', 'pocket', 'zoltan', 'symbolic', 'attributes', 'calculator']
# alternative to lambda
def len_alpha(item):
return ( len(item), item[0] )
sorted_lst3 = sorted(lst, key = len_alpha)
# compare sorted_lst2 and sorted_lst3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment