M14) Converting collections to distinct values

A report needs distinct priority codes in ascending order, stored as a tuple. Listing 1 starts with a list and combines type conversions with sorting.

Listing 1: Convert repeated priority codes into an ordered collection.
codes = [4, 1, 4, 3, 1]
result = tuple(sorted(set(codes)))

What are the type and value of result?

  • A list with value [1, 3, 4].
  • A tuple with value (4, 1, 4, 3, 1).
  • A set containing 1, 3, and 4.
  • A tuple with value (1, 3, 4).
  1. set(values) creates a new set containing each distinct value once; it does not preserve sequence order. For integers, set([8, 8, 6]) contains 8 and 6; an empty input gives an empty set.
  2. sorted(values) returns a new list in ascending order. It keeps duplicates: sorted([8, 6, 8]) gives [6, 8, 8]; an empty input gives [].
  3. tuple(values) collects the supplied values into a tuple in their traversal order. tuple([8, 6]) gives (8, 6); an empty input gives ().

These operations leave their input collections unchanged. All codes here are integers, so they can be placed in a set and compared when sorting.