Sort Lists

 

What You'll Learn: In this tutorial, you'll discover how to sort lists in Python. Sorting helps you organize items in alphabetical or numerical order, making it easier to find and manage them.

Sort List Alphanumerically

You can sort a list of strings or numbers using the sort() method. By default, this sorts the list in ascending (alphabetical or numerical) order.

Example: Sort Alphabetically

python
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
 

Example: Sort Numerically

python
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Output: [23, 50, 65, 82, 100]
 

Sort Descending

To sort the list in descending order, use the reverse = True argument in the sort() method.

Example:

python
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)

Output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
 

Example:

python
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)

Output: [100, 82, 65, 50, 23]
 

Customize Sort Function

You can customize the sort by using the key argument with a function. The function will return a number used to sort the list.

Example: Sort Based on Proximity to 50

python
def myfunc(n):
    return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)

Output: [50, 65, 23, 82, 100]
 

Case Insensitive Sort

The default sort() method is case sensitive, which means uppercase letters come before lowercase letters. To sort without considering case, use str.lower as the key.

Example:

python
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

Output: ['Kiwi', 'Orange', 'banana', 'cherry']
 

Example: Case Insensitive Sort

python
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

Output: ['banana', 'cherry', 'Kiwi', 'Orange']
 

Reverse Order

To reverse the order of the list elements, use the reverse() method.

Example:

python
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)

Output: ['cherry', 'Kiwi', 'Orange', 'banana']
 

Try It Yourself: Fun Exercises

  1. Sort Your Favorite Colors:
    • Create a list of your favorite colors.
    • Sort them alphabetically and then in reverse order.
  2. Order Your Numbers:
    • Create a list of random numbers.
    • Sort them to see the smallest and largest values.

Summary:

In this Python tutorial, we learned how to sort lists alphanumerically, in descending order, and with customized functions. We also explored case insensitive sorting and reversing the order of list items. Sorting helps you organize and manage your data efficiently. Keep experimenting and have fun with sorting lists in Python!