liveBook · Manning

Set

As explained in Python Workout, Second Edition

A set is an unordered collection of distinct hashable values in Python.

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

How Python Workout, Second Edition covers it

How deep it goes
Works through construction, mutation, set operators, subset testing, and list-hashability mistakes without descending into implementation internals.
Examples
Uses duplicate numbers, dictionary-key diffs, unique words in files, server logs, directory extensions, and vowel detection.
What it assumes
Assumes familiarity with Python sequences, dictionaries, iteration, and function calls while reinforcing core data-structure fluency.
What you can do after
Apply it via Python's built-in set operations to deduplicate sequences, compare collections, and count distinct values.
How it connects
Connects sets with dictionaries, dictionary views, lists, strings, files, comprehensions, and regular expressions.

Also explained in

Compare how 15 books explain set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.