How to Sort a List of Numbers in Python with Default Parameters
Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.
Python code
22 linesdef sort_numbers(numbers, reverse=False):
"""Sort a list of numbers in ascending or descending order."""
return sorted(numbers, reverse=reverse)
def main():
numbers = [5, 2, 9, 1, 7, 3]
# Default sort (ascending)
ascending = sort_numbers(numbers)
print(f"Ascending: {ascending}")
# Sort with reverse=True (descending)
descending = sort_numbers(numbers, reverse=True)
print(f"Descending: {descending}")
# Original list remains unchanged
print(f"Original: {numbers}")
if __name__ == "__main__":
main()
Output
Ascending: [1, 2, 3, 5, 7, 9]
Descending: [9, 7, 5, 3, 2, 1]
Original: [5, 2, 9, 1, 7, 3]
How it works
The sort_numbers function uses Python's built-in sorted() which returns a new list, leaving the original unchanged. The reverse parameter defaults to False, allowing the function to sort ascending by default. When reverse=True is passed, it sorts descending. This pattern makes functions flexible without requiring extra arguments on every call.
Common mistakes
- Using `.sort()` on the list inside the function, which modifies the original list
- Forgetting to specify `reverse=True` when descending order is needed
- Assuming the sorted function modifies the original list instead of returning a new one
Variations
- Using `list.sort()` in-place if you don't need to preserve the original list
- Using `key` parameter to sort by a custom function, e.g., `sorted(numbers, key=abs)`
Real-world use cases
- Sorting user records by score in a leaderboard with a toggleable ascending/descending option.
- Ordering log entries by timestamp for analysis, with an option to view most recent first.
- Sorting product prices for an e-commerce sorting feature, where users can switch sort direction.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.