Skip to content

Sorting in place and producing sorted copies [ref]

Problem

  • Sort [3, 1, 2] in place and inspect the return value of sort.
  • Make a sorted copy of [3, 1, 2] without mutating the original.
  • Sort [3, 1, 2] in descending order.
  • Sort the characters of "cab" into a string.
  • Iterate over [1, 2, 3] in reverse without changing it.

Python solution

nums = [3, 1, 2]
result = nums.sort()
(nums, result)  # ([1, 2, 3], None)

nums = [3, 1, 2]
ordered = sorted(nums)
(nums, ordered)  # ([3, 1, 2], [1, 2, 3])

sorted([3, 1, 2], reverse=True)  # [3, 2, 1]

"".join(sorted("cab"))  # 'abc'

nums = [1, 2, 3]
list(reversed(nums))  # [3, 2, 1]
nums                  # [1, 2, 3]