How to Sort a List of Numbers in Python

The challenge

Finish the solution so that it sorts the passed-in array/list of numbers. If the function passes in an empty array/list or null/None value then it should return an empty array/list.


solution([1,2,3,10,5]) # should return [1,2,3,5,10] solution(None) # should return []
Code language: PHP (php)

The solution in Python code

Option 1:

def solution(nums): if not nums: return [] return sorted(nums)
Code language: Python (python)

Option 2:

def solution(nums): return sorted(nums) if nums else []
Code language: Python (python)

Option 3:

def solution(nums): return sorted(nums or [])
Code language: Python (python)

Test cases to validate our solution

import test from solution import solution @test.describe("Fixed Tests") def fixed_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(solution([1,2,3,10,5]), [1,2,3,5,10]) test.assert_equals(solution(None), []) test.assert_equals(solution([]), []) test.assert_equals(solution([20,2,10]), [2,10,20]) test.assert_equals(solution([2,20,10]), [2,10,20])
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments