CodeBlanks Logo Icon CodeBlanks

Summary - Set

Add elements to a set and print it in a mini task.

Summary - Set

In this group you learned what a set is, add and search, intersection and union. A set manages unique elements in O(1).

A set is a powerful tool for data analysis with operations like intersection and union. Duplicates are automatically eliminated.

Practice Union

Write set_union(a, b). Return sorted union of a and b. Print [1, 2, 3, 4] with print(set_union({1,2}, {2,3,4})).

Starter code

solution.py
def set_union(a, b):
    # Union

Sample solution

solution.py
def set_union(a, b):
    # Union
    result = set()
    for x in a:
        result.add(x)
    for x in b:
        result.add(x)
    return sorted(result)
print(set_union({1, 2}, {2, 3, 4}))

Expected output

[1, 2, 3, 4]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Summary - Set: match the terms

Term Meaning
set Unique
add Add
intersection A & B
union A | B

2 Set

Question
A set stores ____ elements.
Answer
A set stores unique elements.

Explanation: unique is right.

3 What happens if the same element is added twice to a set?

  • Added twice
  • Deleted
  • Stays once Correct answer
  • Raises error

Explanation: It stays once, not added again.

All lessons in Beginner