Sorting and copies

sort and sorted, min, max and sum.

There are two ways to sort a list. The method items.sort() changes the list itself and returns None. The function sorted(items) leaves the original list untouched and returns a new, sorted one.

nums = [3, 1, 2]
print(sorted(nums), nums)   # [1, 2, 3] [3, 1, 2]
nums.sort()
print(nums)                 # [1, 2, 3]

The classic mistake is nums = nums.sort(). The method returned None and the list is lost: nums now holds None. Remember the rule: methods that change an object in place (sort, append, reverse) return None.

Reverse order is set with reverse=True: sorted(nums, reverse=True). Strings are sorted alphabetically with case taken into account: capital letters come before lowercase ones. To sort ignoring case, use the key key=str.lower. More about keys in the module "Iterating like a pro".

Numeric lists have ready-made functions: sum(nums), min(nums), max(nums). On an empty list min and max raise ValueError, while sum([]) is 0. The average is sum(nums) / len(nums), but first make sure the list is not empty.

The slice nums[:] and nums.copy() make a shallow copy. The outer list is new, but the nested lists inside it are shared. For nested structures there is copy.deepcopy, but more often it is simpler not to share nested data between parts of the program.

Practice

  1. The result of sort

    What does the program print?

    nums = [3, 1, 2]
    result = nums.sort()
    print(result)
    
  2. sort or sorted

    You need a sorted copy without changing the original list. What will do?

    • sorted(items)
    • items.sort()
    • items = items.sort()
    • items.reverse()
  3. Top scores

    Write a function top(scores, n) that returns the n largest values in descending order. The original list must not change.