A set is an unordered collection of distinct hashable values. Treat it as a dictionary without values: use it when a problem asks for unique items or fast membership lookup. Sets are especially useful with filenames, email addresses, postal codes, IP addresses, and other sequences. section 5.2 section 5.19
Choose the operation that matches the programming task:
- Remove duplicates from a sequence with set(values). section 5.17
- Build an empty set with set(), then add one value using add or many values using update. section 5.17
- Combine dictionary keys with first.keys() | second.keys(), or find shared keys with &; each key is visited once. section 5.13
- Test whether one set contains every item in another with the subset operator <. section 8.27
- Avoid inserting a list as an element: lists cannot be set elements, so use {*numbers} or update(numbers) to add their contents. section 5.17
Count unique words while reading lines
Maintain unique_words = set(). For each line, split it on whitespace and call unique_words.update(words). At the end, len(unique_words) gives the number of distinct words. This keeps counting logic in a dictionary while the set enforces uniqueness. section 6.11
Check for all five vowels
Define vowels = {'a', 'e', 'i', 'o', 'u'} and test vowels < set(word). Converting the string to a set lets one subset comparison replace five membership checks; repeated letters do not change the set. section 8.27
all_keys = first.keys() | second.keys()
Inspect the compact union expression used to collect every key from two dictionaries exactly once. section 5.13














