Reading preferences
Concept

Building Subsets

Grow a power set by deciding whether to include each item.

python, subsets, combinations, enumeration

Include or exclude

Each item can be left out or included. Start with the empty subset; for each item, add a new version of every existing subset containing that item.

Python illustration

def subsets(items):
    result = [[]]
    for item in items:
        result += [group + [item] for group in result]
    return result

print(subsets(["A", "B"]))

Prepared output: [[], ['A'], ['B'], ['A', 'B']].

See the reasoning

Branch on each choice

See exclude and include versions of each existing subset. This is a prepared demonstration, not live code execution.

No items yet

Subsets after each item
  1. Choices[ ]Current focus

The empty subset is the only choice before any items.

The cost of the output

After processing each position, the result contains exactly the choices for the processed prefix: each previous subset appears once without and once with the new item. Equal input values may produce duplicate-looking lists; deduplicating values is a different contract. For n distinct positions there are 2**n subsets. Storing and copying all lists requires O(n * 2**n) time and space in the worst case; even the empty input returns one empty subset.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Why start with one empty subset?
2. What happens when a new distinct item is processed?
3. What if input values repeat?
4. How many subsets do n distinct positions produce?

References and further reading