
# Every Python list has a sort method that sorts it **in place.**

x = [4,1,2,3]
print(x)
x.sort()		# Sort x IN PLACE
print(x)

# If you don’t want to mess up your list, you can use the "sorted" function, 
# which returns a new list: 

x = [4,1,2,3]
print(x)
y = sorted(x) 
print("x = ", x)
print("y = ", y)

# sort() and sorted() has additional (named) argument with default values...
#
#    key = (default) No function
#    reverse = (default) False

# sort the list by absolute value from largest to smallest

x = [-4,1,-2,3]
print("\nx = ", x)

y = sorted(x)
print("sorted(x) = ", y)		# [-4,-2,1,3]

y = sorted(x, key=abs) 		
print("sorted(x, abs) =", y)		# [1,-2,3,-4]

y = sorted(x, key=abs, reverse=True) 		
print("sorted(x, abs, reverse=True) =", y)		


# ##################################################################
# Advance use of "key": example 1
#
#           Sort the words by length:

x = ["a", "abc", "xyz", "ab", "k"]

print("\nx = ", x)

y = sorted(x)
print("sorted(x) = ", y)   


y = sorted(x, key=len)
print("sorted(x, len) = ", y)

# ##################################################################
# Advance use of "key": example 2
#
#       sort the words and counts from highest count to lowest

word_counts = { "the":3, "way":1,  "blue": 5 }

print("\nword_counts = ", word_counts)
print("word_counts.items() = ", word_counts.items(), "\n")

# NOTE: sorted(list) - NEEDS to use a list !!!

y = sorted(word_counts.items() ) 
print("sorted(word_counts) = ", y)

# sort the words by its counts 
y = sorted(word_counts.items(), key=lambda word_and_count: word_and_count[1] )
print("sorted(word_counts) by counts = ", y)


