YouTip LogoYouTip

Python Sort By Length

## Python: How to Sort a List by Element Length In Python, sorting a list of elements (such as strings, tuples, or other collections) based on their length is a common task. This can be easily achieved using Python's built-in `sorted()` function or the `list.sort()` method. By leveraging the `key` parameter and passing Python's built-in `len` function, you can customize the sorting behavior to evaluate the length of each element rather than its alphabetical or numerical value. --- ## Syntax and Methods Python provides two primary ways to sort a list: 1. **`sorted(iterable, key=len, reverse=False)`**: A built-in function that returns a **new** sorted list, leaving the original list unchanged. 2. **`list.sort(key=len, reverse=False)`**: A list method that sorts the list **in-place** (modifying the original list) and returns `None`. ### Parameters: * **`key`**: A function that serves as a systematic key for sort comparison. Passing `len` tells Python to calculate the length of each element and sort based on those values. * **`reverse`**: A boolean value. If set to `True`, the list will be sorted in descending order (longest to shortest). The default is `False` (shortest to longest). --- ## Code Examples ### Example 1: Basic Sorting Using `sorted()` (Ascending Order) The `sorted()` function is ideal when you want to keep the original list intact and generate a new sorted list. ```python # Define a list containing strings of various lengths words = ["apple", "banana", "kiwi", "cherry", "mango"] # Use the sorted() function with key=len to sort by string length sorted_words = sorted(words, key=len) # Output the original and sorted lists print("Original list:", words) print("Sorted list (by length):", sorted_words) ``` **Output:** ```text Original list: ['apple', 'banana', 'kiwi', 'cherry', 'mango'] Sorted list (by length): ['kiwi', 'apple', 'mango', 'cherry', 'banana'] ``` #### Code Explanation: 1. `words` is the initial list containing five string elements. 2. `sorted(words, key=len)` processes each element in `words` through the built-in `len()` function. 3. Python compares the integer lengths returned by `len()` (e.g., `kiwi` is 4, `apple` is 5, `banana` is 6) and sorts the elements from shortest to longest. 4. The result is saved into a new variable, `sorted_words`. --- ### Example 2: In-Place Sorting Using `list.sort()` If you do not need to preserve the original order of the list, sorting in-place is more memory-efficient. ```python # Define a list of strings languages = ["Python", "C", "Java", "Go", "Rust"] # Sort the list in-place by length languages.sort(key=len) # Output the modified list print("Sorted list in-place:", languages) ``` **Output:** ```text Sorted list in-place: ['C', 'Go', 'Java', 'Rust', 'Python'] ``` --- ### Example 3: Sorting by Length in Descending Order (Longest to Shortest) To sort elements from longest to shortest, simply set the `reverse` parameter to `True`. ```python # Define a list of strings animals = ["cat", "elephant", "dog", "hippopotamus", "giraffe"] # Sort by length in descending order longest_to_shortest = sorted(animals, key=len, reverse=True) print("Sorted list (longest to shortest):", longest_to_shortest) ``` **Output:** ```text Sorted list (longest to shortest): ['hippopotamus', 'elephant', 'giraffe', 'cat', 'dog'] ``` --- ## Key Considerations ### 1. Stable Sorting (Tie-Breaking) Python's sorting algorithms (Timsort) are **stable**. This means that if multiple elements have the same length, their original relative order is preserved in the sorted list. For example, in **Example 1**: * `"apple"` (length 5) and `"mango"` (length 5) have the same length. * Because `"apple"` appeared before `"mango"` in the original list, it remains before `"mango"` in the sorted list: `['kiwi', 'apple', 'mango', ... ]`. ### 2. Sorting Lists of Other Iterables The `key=len` parameter is not limited to strings. It works on any list containing elements that support the `len()` function, such as lists of lists, tuples, or dictionaries. ```python # A list of lists with different lengths nested_list = [[1, 2, 3], , [5, 6]] # Sort the nested lists by their length nested_list.sort(key=len) print("Sorted nested list:", nested_list) # Output: [, [5, 6], [1, 2, 3]] ```
← Python If ElsePython Empty List β†’