python How sort list in one line and return it

Learn python how sort list in one line and return it with practical examples, diagrams, and best practices. Covers python, list, sorting development techniques with visual explanations.

Python List Sorting: One-Liner Solutions for Sorted Returns

Hero image for python How sort list in one line and return it

Discover efficient Python one-liner techniques to sort lists and return a new sorted list without modifying the original, using sorted() and list comprehensions.

Sorting lists is a fundamental operation in Python programming. While Python offers various ways to sort, often the goal is to achieve this in a concise, readable manner, especially when you need a new sorted list without altering the original. This article explores the most common and Pythonic one-liner solutions for sorting lists and returning the result, focusing on the built-in sorted() function.

The sorted() Function: Your Go-To for One-Liner Sorting

Python's built-in sorted() function is the primary tool for sorting any iterable (including lists, tuples, strings, etc.) and returning a new sorted list. This is crucial when you need to preserve the original order of your data. It's highly versatile, supporting various data types and offering customization options for sorting order and keys.

my_list = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_list = sorted(my_list)

print(f"Original list: {my_list}")
print(f"Sorted list: {sorted_list}")

# Output:
# Original list: [3, 1, 4, 1, 5, 9, 2, 6]
# Sorted list: [1, 1, 2, 3, 4, 5, 6, 9]

Basic usage of sorted() for ascending order.

Customizing Sort Order and Keys

The sorted() function provides powerful arguments to customize the sorting behavior. You can sort in descending order using the reverse=True argument, or sort based on a custom key using the key argument, which accepts a function to extract a comparison key from each list element.

numbers = [3, 1, 4, 1, 5, 9]

# Sort in descending order
desc_sorted = sorted(numbers, reverse=True)
print(f"Descending sorted: {desc_sorted}")

words = ["banana", "apple", "cherry", "date"]

# Sort by length of the word
sorted_by_length = sorted(words, key=len)
print(f"Sorted by length: {sorted_by_length}")

# Sort by the last character of the word
sorted_by_last_char = sorted(words, key=lambda word: word[-1])
print(f"Sorted by last char: {sorted_by_last_char}")

# Output:
# Descending sorted: [9, 5, 4, 3, 1, 1]
# Sorted by length: ['date', 'apple', 'banana', 'cherry']
# Sorted by last char: ['banana', 'apple', 'date', 'cherry']

Using reverse and key arguments with sorted().

flowchart TD
    A[Start with original list] --> B{Call sorted() function}
    B --> C{Specify 'reverse=True'?}
    C -- Yes --> D[Sort in descending order]
    C -- No --> E[Sort in ascending order]
    B --> F{Specify 'key' function?}
    F -- Yes --> G[Apply key function to each element]
    F -- No --> H[Use default comparison]
    D --> I[Return new sorted list]
    E --> I
    G --> I
    H --> I
    I --> J[End]

Decision flow for sorted() function parameters.

Sorting Lists of Complex Objects

When dealing with lists of custom objects or dictionaries, the key argument becomes indispensable. You can use lambda functions or operator.itemgetter and operator.attrgetter for more concise and efficient key extraction.

from operator import itemgetter, attrgetter

# List of dictionaries
students = [
    {'name': 'Alice', 'age': 25, 'grade': 'A'},
    {'name': 'Bob', 'age': 22, 'grade': 'C'},
    {'name': 'Charlie', 'age': 23, 'grade': 'B'}
]

# Sort by age using lambda
sorted_by_age_lambda = sorted(students, key=lambda s: s['age'])
print(f"Sorted by age (lambda): {sorted_by_age_lambda}")

# Sort by grade using itemgetter
sorted_by_grade_itemgetter = sorted(students, key=itemgetter('grade'))
print(f"Sorted by grade (itemgetter): {sorted_by_grade_itemgetter}")

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price
    def __repr__(self):
        return f"Product('{self.name}', {self.price})"

products = [
    Product('Laptop', 1200),
    Product('Mouse', 25),
    Product('Keyboard', 75)
]

# Sort by price using attrgetter
sorted_products_by_price = sorted(products, key=attrgetter('price'))
print(f"Sorted products by price: {sorted_products_by_price}")

Sorting complex data structures using lambda, itemgetter, and attrgetter.