Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresJuniorCommonPractical

What is a Python set built for, and what do the union, intersection and difference operators do?

Answer

A set stores unique, hashable elements with no defined order and gives O(1) average membership testing, making it ideal for deduplication and fast `in` checks. `|` computes the union (all elements from either set), `&` computes the intersection (elements in both), `-` computes the difference (elements in the left set but not the right), and `^` computes the symmetric difference (elements in exactly one of the two sets).

Strong answer includes

  • unique hashable elements, fast membership test
  • union, intersection, difference, symmetric difference operators
  • good for deduplication

Practical example

Deduplicate and compare ID sets
Python
editable · browser sandbox
Result
Run the code to see the result.

Set difference finds IDs that exist only in the incoming set, intersection finds IDs present in both, and union combines both sets without duplicates.

Expected result: {104, 105}; {102, 103}; and one set containing 101 through 105 (set display order is not guaranteed).

#set#collections

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules