List sort method orders a list in place.
By default sorts in ascending order.
You can modify sort behavior by passing in keyword arguments.
A special "name=value" syntax in function calls that specifies passing by name and is often used for giving configuration options.
In sorts, the reverse argument sorts list in descending order.
The key argument gives a one-argument function that returns the value to be used in sorting.
The string object's standard lower case converter in the following convert string to lower case during sorting:
L = ['abc', 'ABD', 'aBe'] L.sort() # Sort with mixed case print( L ) L = ['abc', 'ABD', 'aBe'] L.sort(key=str.lower) # Normalize to lowercase print( L ) L = ['abc', 'ABD', 'aBe'] L.sort(key=str.lower, reverse=True) # Change sort order print( L )
The sort key argument is useful when sorting lists of dictionaries to pick out a sort key by indexing each dictionary.
Sorting is also available in recent Pythons as a built-in function, which sorts any collection and returns a new list for the result instead of in-place changes:
L = ['abc', 'ABD', 'aBe'] print( sorted(L, key=str.lower, reverse=True) ) # Sorting built-in # from w w w .j a v a 2 s . com L = ['abc', 'ABD', 'aBe'] print( sorted([x.lower() for x in L], reverse=True) ) # Pretransform items: differs!
Here, the last example here converts to lowercase prior to the sort with a list comprehension.
The result does not contain the original list's values as it does with the key argument.
The latter is applied temporarily during the sort, instead of changing the values to be sorted altogether.