# for more information about python's lambda functions, see e.g. here
# https://docs.python.org/3.5/tutorial/controlflow.html#lambda-expressions
# using lambda functions as the "key" argument to sorted() (works also with sort)
# more information on using key is available e.g. here:
# https://wiki.python.org/moin/HowTo/Sorting#Key_Functions
# generating a new, sorted list
# using the default string order
sorted(["red","lefty","poncho","dafna"])
# this time sorting according to the strings' length
# using the default integer order
# "lefty" precedes "dafna" because cpython's sort is *stable*
# i.e., maintains the relative order of records with equal keys
# https://en.wikipedia.org/wiki/Sorting_algorithm#Stability
sorted(["red","lefty","poncho","dafna"],key=len)
# same as last one, but we send our own lambda function
# which simply calls len()
sorted(["red","lefty","poncho","dafna"],key=lambda s:len(s))
# default string sorting according to the reversed strings
# note that the reversed strings are used for sorting,
# but the sorted list includes the original (non-reversed) strings
sorted(["red","lefty","poncho","dafna"],key=lambda s:s[::-1])
# default string sorting according to the first character
sorted(["romeo","red","almo"],key=lambda s:s[0])
# same as last one, but we define the function with def and give it a name
def first_char(s):
return s[0]
sorted(["romeo","red","almo"],key=first_char)
# sotring by numerical values
sorted(["3","222","11"],key=int)
# sotring by numerical values of hex representation
sorted(["3","222","1a"],key=lambda s:int(s,16))