Sort List Alphanumerically
Every list has a sort() method. Unless you tell it otherwise, it arranges items alphanumerically in ascending order.
Example
Put strings in alphabetical order:
Output: complete Python program
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Example
Put numbers in numerical order:
Output: complete Python program
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
Sort Descending
For descending order, pass the keyword argument reverse = True.
Example
Sort strings in descending order:
Output: complete Python program
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Example
Sort numbers in descending order:
Output: complete Python program
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Customize Sort Function
Sorting can also follow a rule of your own: pass a function with the keyword argument key = function.
That function returns a value for each item, and the items are arranged by those values, lowest first.
Example
Order the numbers by their distance from 50:
Output: complete Python program
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
Case Insensitive Sort
Out of the box, sort() is case sensitive, so every capital letter comes before any lower case letter.
Example
A case-sensitive sort may surprise you:
Output: complete Python program
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)
Example
Ignore case while sorting the list:
Output: complete Python program
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
Reverse Order
Sometimes you simply want the items flipped, whatever their alphabetical order.
That is what the reverse() method does: it turns the current order of the elements around.
Example
Flip the order of the items:
Output: complete Python program
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)