4. Sets and uniqueness
A set is an unordered collection with unique elements: duplicates are removed automatically. You write one with curly braces and commas:
Because a set is unordered, its printed order is not guaranteed. To get a stable order, sort it first: sorted(numbers) returns a list.
set(iterable) builds a set from any collection, which is the usual way to remove duplicates from a list:
iterable— a collection to read values from, such as a list or a tuple.
An empty set is written set(). {} is not an empty set; it creates an empty dictionary, which you will meet in a later chapter.
Sets support len(set) and the in operator. They also have methods to change them:
add(value)changes the set in place and returnsNone.discard(value)also changes it in place and returnsNone; it does not raise an error when the value is missing.
Set elements must be immutable. Numbers, strings and tuples can be elements; lists cannot.
Coming from JavaScript? A set is a JS Set, written with {...}. Careful: {} is an empty dict, so an empty set is set().
Create a set
A set literal uses curly braces. Duplicate values are stored only once. Create numbers = {1, 2, 2, 3, 3, 3} and print its elements in ascending order with sorted(numbers).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Length of a set
len(set) returns how many unique elements it has. Create colors = {"red", "green", "blue"} and print its length.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove duplicates from a list
set(iterable) builds a set from another collection. Create letters = ["a", "b", "a", "c", "b"], convert it to a set named unique, and print the sorted result.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Create an empty set
An empty set must be created with set(); {} creates an empty dictionary instead. Create empty = set() and print its length.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Check membership in a set
The in operator works on sets and returns True or False. Create fruits = {"apple", "banana", "cherry"}, then print whether "banana" is in it and whether "grape" is in it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add a value
set.add(value) adds value to the set if it is not already there. Create tags = {"python", "code"}, add "web", and print the sorted set.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Remove a value
set.discard(value) removes value if it is present and does nothing if it is missing. Create tags = {"python", "code"}, discard "code", and print the sorted set.
Print exactly:
Create a free account to save your progress and unlock chapter 2.