18  The Round Table: Basic Sorting in Python

Today, we gather at the Round Table to learn the art of sorting. Just as King Arthur’s knights had their proper places around the table, we’ll learn how to arrange elements in Python lists in a specific order. We’ll master three powerful sorting techniques: sorted(), .sort(), and reverse sorting.

18.1 1. The sorted() Function: Creating a New Sorted List

The sorted() function is like a magical spell that creates a new, sorted version of a list without changing the original. It’s perfect when you want to keep your original list intact.

# Original list of knights
knights = ["Lancelot", "Galahad", "Parzival", "Gawain", "Bors"]

# Create a new sorted list
sorted_knights = sorted(knights)

print("Original knights:", knights)
print("Sorted knights:", sorted_knights)

This will output:

Original knights: ['Lancelot', 'Galahad', 'Parzival', 'Gawain', 'Bors']
Sorted knights: ['Bors', 'Galahad', 'Gawain', 'Lancelot', 'Parzival']

Notice how the original knights list remains unchanged, while sorted_knights is a new, alphabetically sorted list.

18.2 2. The .sort() Method: Sorting a List in Place

The .sort() method is like rearranging the actual seats at the Round Table. It modifies the original list directly, which can be more memory-efficient but changes your original data.

# List of quest items
quest_items = ["Holy Grail", "Excalibur", "Round Table", "Magic Scabbard"]

# Sort the list in place
quest_items.sort()

print("Sorted quest items:", quest_items)

This will output:

Sorted quest items: ['Excalibur', 'Holy Grail', 'Magic Scabbard', 'Round Table']

The quest_items list is now sorted alphabetically, and the original order is lost.

18.3 3. Reverse Sorting: From Z to A

Sometimes, you might want to sort in reverse order, like listing the knights from Z to A. Both sorted() and .sort() can do this with the reverse parameter.

Using sorted():

# List of magical creatures
creatures = ["Dragon", "Unicorn", "Griffin", "Phoenix", "Merlin"]

# Create a new reverse-sorted list
reverse_sorted_creatures = sorted(creatures, reverse=True)

print("Original creatures:", creatures)
print("Reverse sorted creatures:", reverse_sorted_creatures)

This will output:

Original creatures: ['Dragon', 'Unicorn', 'Griffin', 'Phoenix', 'Merlin']
Reverse sorted creatures: ['Unicorn', 'Phoenix', 'Merlin', 'Griffin', 'Dragon']

Using .sort():

# List of quest difficulties
difficulties = ["Easy", "Medium", "Hard", "Legendary"]

# Sort the list in place in reverse order
difficulties.sort(reverse=True)

print("Sorted difficulties (hardest to easiest):", difficulties)

This will output:

Sorted difficulties (hardest to easiest): ['Medium', 'Legendary', 'Hard', 'Easy']

18.4 Sorting Numbers

Sorting isn’t just for words! Let’s see how it works with numbers:

# Knight power levels
power_levels = [5000, 9000, 1000, 7500, 500]

# Sort power levels (lowest to highest)
sorted_powers = sorted(power_levels)
print("Sorted power levels:", sorted_powers)

# Sort power levels in place (highest to lowest)
power_levels.sort(reverse=True)
print("Power levels from strongest to weakest:", power_levels)

This will output:

Sorted power levels: [500, 1000, 5000, 7500, 9000]
Power levels from strongest to weakest: [9000, 7500, 5000, 1000, 500]

18.5 Practice Your Sorting Magic

Now it’s your turn to practice the art of sorting:

  1. Create a list of at least 5 Arthurian locations. Use sorted() to create a new, alphabetically sorted list of these locations.

  2. Make a list of the ages of at least 5 knights. Use the .sort() method to arrange these ages from youngest to oldest.

  3. Create a list of the years of famous battles. Use either sorted() or .sort() to arrange these years from most recent to oldest (remember to use reverse sorting!).

Here’s a starting point for your quests:

# Quest 1: Sorting Arthurian Locations
locations = ["Camelot", "Avalon", "Tintagel", "Camlann", "Corbenic"]
# Your code here

# Quest 2: Sorting Knight Ages
knight_ages = [25, 40, 35, 30, 45]
# Your code here

# Quest 3: Sorting Battle Years
battle_years = [516, 490, 508, 520, 500]
# Your code here

18.6 Common Bugs to Watch Out For

As you practice your sorting spells, be wary of these common pitfalls:

  1. Forgetting that sorted() creates a new list: If you use sorted() but don’t assign the result to a new variable, your original list won’t be affected.

  2. Mistaking .sort() for sorted(): Remember, .sort() modifies the original list and returns None, while sorted() creates a new list.

  3. Sorting mixed data types: Be careful when sorting lists with mixed data types (like numbers and strings together). This can lead to unexpected results or errors.

  4. Forgetting the parentheses in .sort(): It’s .sort(), not .sort. Forgetting the parentheses will reference the method without calling it.

Remember, young knights, the power to bring order to chaos is a noble and useful skill. With these sorting techniques, you can arrange any list to your liking. Keep practicing, and soon you’ll be sorting with the speed and precision of Merlin himself!