Python Set Construction and Unique Values
Core idea
A set stores distinct hashable values without a guaranteed position or insertion order. Use {2, 5} for a nonempty set and set() for an empty one. Convert a list with set(values) to discard repeated equal values. To display predictable results for integers or strings of the same type, use sorted(s), which returns a sorted list.
badges = [8, 3, 8, 5]unique = set(badges)print(sorted(unique))print(len(unique))Three distinct numbers remain; sorting is only for display.
Start with an empty set
type() identifies the type; its name attribute gives the name. The empty braces create a dictionary.
Use hashable coordinates
positions = {(1, 2), (1, 2), (2, 3)}print(len(positions))Tuples of integers are hashable, so equal coordinates collapse into one member.
Common mistake
Lists are not hashable: set([[1, 2]]) raises TypeError. Sets cannot be indexed; converting a set to a list does not recover the original order.
Practice
Create a list of five badge numbers including two repeats. Convert it to a set and print the sorted unique numbers and their count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set construction
Check your understanding of set construction.
What is printed?
print(len({4, 4, 9}))What is printed?
print(type({}).__name__)What happens?
set([[2, 3]])Which produces a predictable ascending list of distinct integer values?