How to Sort Lists Using Custom Keys in Python

1. Introduction

Sorting is a fundamental operation in programming that organizes elements of a collection in a specified order. In Python, lists can be easily sorted using the sort() method or the sorted() function. While these tools work well for simple cases, Python also provides the ability to sort using custom keys, which allows for more control over the sorting process, especially when dealing with complex data structures.

Definition

Sorting with custom keys in Python involves using a function that is passed as an argument to the key parameter of the sort() method or the sorted() function. This function computes a key value for each element in the list, and the elements are sorted based on these key values rather than their actual values.

2. Program Steps

1. Define a list that you want to sort.

2. Define a custom key function that will return a value that Python will use for sorting the list elements.

3. Use the sorted() function or sort() method and pass the custom key function to the key parameter.

4. Print the sorted list to verify the order.

3. Code Program

# Step 1: Define a list
unsorted_list = ['banana', 'cherry', 'apple']

# Step 2: Define a custom key function
def custom_sort_key(word):
    """Return the third character of a string as the sort key."""
    return word[2]

# Step 3: Sort the list using the custom key
sorted_list = sorted(unsorted_list, key=custom_sort_key)

# Step 4: Print the sorted list
print(sorted_list)

Output:

['banana', 'apple', 'cherry']

Explanation:

1. unsorted_list contains a list of strings ['banana', 'cherry', 'apple'].

2. custom_sort_key is a function that takes a string and returns its third character.

3. sorted_list is created by calling sorted() on unsorted_list and passing custom_sort_key to the key parameter, which sorts the list based on the third letter of each word.

4. The print function outputs the sorted_list.

5. The result demonstrates that the list is sorted based on the third character of each word, resulting in the order: ['banana', 'apple', 'cherry'].

Comments