Home › Learn › Python › Dictionaries, tuples, and sets

Sets

Lesson 24 of 40. Unordered collections with no duplicates, fast membership.

A set holds each value once: set([1, 2, 2, 3]) is {1, 2, 3}. Adding a duplicate does nothing. in is fast even for huge sets, which is the main practical reason to use one. Sets have no order, so convert to a list and sort when you need a predictable sequence.

a & b is the intersection (in both), a | b the union, a - b the difference. len(set(items)) < len(items) is the one-line way to ask whether a list has duplicates.

seen = set()
seen.add("x")
seen.add("x")
print(len(seen))          # 1
print({1, 2, 3} & {2, 3, 4})   # {2, 3}

Your task

Write unique_sorted(items) returning the distinct items as a sorted list, common(a, b) returning the items present in both lists, sorted, and has_duplicates(items) returning True when any value appears more than once.

Hint 1

sorted(set(items))

Hint 2

sorted(set(a) & set(b)); duplicates: len(set(items)) != len(items)

Show the solution
def unique_sorted(items):
    return sorted(set(items))


def common(a, b):
    return sorted(set(a) & set(b))


def has_duplicates(items):
    return len(set(items)) != len(items)

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.