Changing letter cases isn't the only thing you can do with the key
parameter. You can also pass in other functions, such as len()
. This is another common key
argument; it sorts strings according to their length. Take a look:
products = ['SuperPower3000', 'maxVoltage 2', 'ELECTROKING', 'aMpLiFiEr 52S','AlternatingCurrent', 'el3ctric 2.0']
print(sorted(products, key=len))
The product names will now be sorted according to their length. Note that the syntax is a bit different in this case: We skipped the str
prefix in the key
parameter. This is because str.lower
only applies to strings, whereas len()
can be used with many variable types.
Of course, you can also use both key
and reverse
in sorted()
and sort()
functions. Here's an example:
print(sorted(products, key=len, reverse=True))