Problem No 9
Sort a list of numbers ascending and descending
Easy≈ 10 minute session
Lesson guide
What this Python exercise practices
Sort a list of numbers ascending and descending is a beginner practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 10 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Beginner
- Estimated time
- 10 minutes
Practice path
Summary
Return a sorted copy of a list of numbers in ascending or descending order.
Problem statement
Write a function sort_numbers(nums, reverse=False) that takes a list of numbers (ints and/or floats) and returns a new list sorted in ascending order when reverse is False, or in descending order when reverse is True. Do not mutate the original list.
Task
Implement a function to return a new list sorted in ascending order by default or descending when requested.
Examples
Ascending sort (default)
Input
sort_numbers([3, 1, 2])
Output
[1, 2, 3]
Explanation
Default returns numbers sorted ascending.
Input format
A list of numbers and an optional boolean reverse flag.
Output format
A new list of numbers sorted in the requested order.
Constraints
Should handle empty lists and a mix of ints and floats. Aim for O(n log n) time using Python's sorting facilities.
Samples
Sample input 0
sort_numbers([3, 1, 2], True)
Sample output 0
[3, 2, 1]
Explanation 0
reverse=True returns numbers sorted descending.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.