Sets

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? s = {9, 3, 3, 5, 5, 2} print(len(s))

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Sets explained

    A set in Python is an unordered collection in which each value appears at most once. Sets are useful for removing duplicates and for fast membership tests, and they support the usual operations of union, intersection and difference.

    Create a set with curly braces, such as {1, 2, 2, 3}, which stores only 1, 2 and 3. To create an empty set, use set(), because empty braces create an empty dictionary instead.

    Set items must be hashable, so numbers, strings and tuples of such values are allowed, but lists are not. Items have no fixed position, so a set cannot be indexed. A membership test with in is fast on average, because a set uses hashing rather than checking every item.

    Python sets support the usual set operations through operators: the vertical bar gives the union, the ampersand gives the intersection, the minus sign gives the difference, and the caret gives the symmetric difference, which holds the items in exactly one of the two sets. The same operations are available as methods, such as union().

    Worked example

    a = {1, 2, 3, 4}
    b = {3, 4, 5}
    print(a | b)
    print(a & b)
    print(a - b)
    print(len(a | b))
    
    1. Union: {1,2,3,4}∪{3,4,5}={1,2,3,4,5}\{1, 2, 3, 4\} \cup \{3, 4, 5\} = \{1, 2, 3, 4, 5\}, which has 5 items.
    2. Intersection: {1,2,3,4}∩{3,4,5}={3,4}\{1, 2, 3, 4\} \cap \{3, 4, 5\} = \{3, 4\}.
    3. Difference: {1,2,3,4}∖{3,4,5}={1,2}\{1, 2, 3, 4\} \setminus \{3, 4, 5\} = \{1, 2\}.

    Check: the union has 4+3−2=54 + 3 - 2 = 5 items, because the two shared items are counted once.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? s = {7, 1, 2, 5, 7} print(len(s))

    • Medium

      What does this Python code print? a = {6, 3, 2, 7, 5} b = {9, 2, 6} print(len(a | b))

    • Hard

      What does this Python code print? print(sorted({x * x % 5 for x in range(4)})[-1])