First page Back Continue Last page Overview Graphics

sort with Key Function

Both list.sort() and sorted() have an optional key parameter to specify a function to be called on each list element prior to making comparisons.

>>> lst = ["Apple","House","cars","Cats","Red","all"]

>>> sorted(lst)

['Apple', 'Cats', 'House', 'Red', 'all', 'cars']

>>> sorted(lst, key=str.lower)

['all', 'Apple', 'cars', 'Cats', 'House', 'Red']