Search notes:

Python: sorted

a = [7, 5, 1, 9, 6, 2, 3, 8, 4]

print sorted(a)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

print a
# [7, 5, 1, 9, 6, 2, 3, 8, 4]

a.sort()
print a
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Github repository about-python, path: /builtin-functions/sorted/simple.py

Sorting a list based on a characteristic their elements

sorted() has an optional key parameter that can be used to sort the elements based on a given characteristic rather than the elements themselves.
In the following example, key transforms each element to their uppercase equivalent to sort strings alphabetically. Without using the key parameter, uppercase letters are sorted before lowercase letters:
words = 'one', 'TWO', 'three', 'four', 'Five'

for word in sorted(words):
    print(word)

print('')

for word in sorted(words, key = lambda w: w.upper()):
    print(word)
Github repository about-python, path: /builtin-functions/sorted/key.py
Compare with the same functionality in the sort() method.

Sorting user defined types

In order to be able to use sorted on user defined types, the type needs to implement the __lt__ dunder.
class CLS:

      def __init__(self, val):

          self.val = val

      def __lt__(self, other):
          return self.val < other.val

      def __repr__(self):
          return 'CLS(' + str(self.val) + ')'


L = [ CLS(10),  CLS( 4), CLS(22), CLS( 8) ]

print(sorted(L))
#
#  [CLS(4), CLS(8), CLS(10), CLS(22)]
Github repository about-python, path: /builtin-functions/sorted/user-defined-class.py
If __lt__ hadn't been defined, sorting these object would have resulted in a TypeError exception (TypeError: '<' not supported between instances of 'CLS' and 'CLS').

See also

list.sort()
Python: Built in functions

Index