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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
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

  1. Using `list.sort()` in-place if you don't need to preserve the original list
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.