Python Set
A Python set is a mutable collection of unique values with no positions. set([1, 2, 2, 3]) produces {1, 2, 3}, discarding duplicates, and set("foo") produces the distinct characters. Braces also create a set, {1, 2, 3}, but {} creates an empty dictionary, so an empty set must be written set().
Because a set has no order, it supports no indexing or slicing: values[0] raises TypeError: 'set' object is not subscriptable. Iteration works, but the sequence it produces is not meaningful and no iteration order is guaranteed, including for integers; sort before displaying when order matters. For an absent element, remove() raises KeyError while discard() does nothing. The set itself can change through add(), discard(), and remove(), while its elements must be hashable, so a tuple is allowed only when every item is hashable; lists are not allowed. Equal numeric values such as 1, 1.0, and True occupy one set element. A frozenset is the immutable variant, usable as a dictionary key.
Four operators compare two sets: & intersection keeps what both have, | union keeps everything, - difference keeps what only the left side has, and ^ symmetric difference keeps what exactly one side has. The named methods intersection(), union(), difference(), and symmetric_difference() do the same and also accept any iterable. Union, intersection, and symmetric difference give the same result with the operands swapped; difference does not.
Use a set for two questions: how many distinct values are there, and have I seen this one before. A membership test in a set is computed from the value’s hash rather than by comparing against each element in turn, so lookup is typically fast on average, though collisions and equality checks can increase the work, while the same test on a list scans. Deduplicating with a set does lose the original order; list(dict.fromkeys(values)) keeps first-seen order instead.
References: Set types, Sets tutorial. See it in use in Python Collections and Comprehensions.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
