Set
A set is an unordered collection of unique items. Sets are mutable which means that elements can be added and removed. All elements in a set must be immutable and hashable (like strings, numbers, or tuples). Sets are unordered and unindexed, meaning elements cannot be accessed by position.
Key Properties of Sets
- No duplicates: Each element appears only once in a set
- Unordered: Elements have no defined order
- Unindexed: Elements cannot be accessed by index
- Immutable elements: All elements must be hashable (immutable)
- Special boolean handling:
Falseand0are treated as duplicates, as areTrueand1
Creating a Set
Sets can be created using curly braces {} or the set() constructor:
# Using curly bracesnumbers = {1, 2, 3, 4, 5}empty_set = set()When creating a set, duplicate values are automatically removed:
# Using set() constructor with an iterablechars = set("hello") # {'h', 'e', 'l', 'o'} (duplicates removed)numbers = set([1, 2, 3, 1, 2, 3]) # {1, 2, 3}False and 0 are treated as the same value, as are True and 1:
S = {"A", "B", "A", 1, False, True, 0}print(S) # {'A', 'B', False, True} or {'A', 'B', 0, 1}# Note: The set contains either False or 0 (not both), and either True or 1 (not both)Warning
An empty set must be created using
set(), not{}. The empty curly braces{}create an empty dictionary, not a set.
Note
Since sets are unordered, the order of elements when printing may vary. The important thing is that all unique elements are present.
Checking Membership
Elements can be checked for existence in a set using the in and not in operators:
numbers = {1, 2, 3, 4, 5}
print(3 in numbers) # Trueprint(10 in numbers) # Falseprint(2 not in numbers) # FalseLooping Over a Set
Sets can be iterated over using a for loop:
S = {1, 2, 3, 4, 5}
for element in S: print(element)Tip
Since sets are unordered, the iteration order is not guaranteed and may vary between runs.
Adding Elements to a Set
There are several ways to add elements to a set:
add(element): Adds a single element to the set.update(iterable1, iterable2, ...): Adds all elements from one or more iterables to the set .intersection_update(iterable1, iterable2, ...): Keeps only elements that are common to the set and all given iterables .symmetric_difference_update(iterable): Keeps only elements that are in the set or in the iterable, but not in both .
numbers = {1, 2, 3}numbers.add(4)print(numbers) # {1, 2, 3, 4}
numbers.add(2) # Adding duplicate has no effectprint(numbers) # {1, 2, 3, 4}
numbers = {1, 2, 3}numbers.update([4, 5, 6], {7, 8})print(numbers) # {1, 2, 3, 4, 5, 6, 7, 8}
numbers = {1, 2, 3, 4, 5}numbers.intersection_update({2, 3, 4}, {3, 4, 5})print(numbers) # {3, 4}
numbers = {1, 2, 3, 4}numbers.symmetric_difference_update({3, 4, 5, 6})print(numbers) # {1, 2, 5, 6}Removing Elements from a Set
There are several ways to remove elements from a set:
remove(element): Removes the specified element from the set. If the element doesn’t exist, it raises aKeyError.discard(element): Removes the specified element from the set. If the element doesn’t exist, it does nothing (no error is raised).difference_update(iterable1, iterable2, ...): Removes all elements that are present in any of the given iterables .pop(): Removes and returns an arbitrary (random) element from the set. If the set is empty, it raises aKeyError.clear(): Removes all elements from the set.
numbers = {1, 2, 3, 4, 5}numbers.remove(3)print(numbers) # {1, 2, 4, 5}
numbers.remove(10) # KeyError: 10
numbers = {1, 2, 3, 4, 5}numbers.discard(3)print(numbers) # {1, 2, 4, 5}
numbers.discard(10) # No error, set remains unchangedprint(numbers) # {1, 2, 4, 5}
numbers = {1, 2, 3, 4, 5}numbers.difference_update({2, 3}, {4})print(numbers) # {1, 5}
numbers = {1, 2, 3, 4, 5}element = numbers.pop()print(element) # Could be any element (e.g., 1, 2, 3, 4, or 5)print(numbers) # Remaining elements
empty = set()empty.pop() # KeyError: 'pop from an empty set'
numbers = {1, 2, 3, 4, 5}numbers.clear()print(numbers) # set()Set Operations and Methods
Sets support various mathematical set operations that return new sets:
union(iterable1, iterable2, ...): Returns a new set containing all elements from the set and all given iterables .intersection(iterable1, iterable2, ...): Returns a new set containing only elements that are common to the set and all given iterables .difference(iterable1, iterable2, ...): Returns a new set containing elements that are in the set but not in any of the given iterables .symmetric_difference(iterable): Returns a new set containing elements that are in either the set or the iterable, but not in both .issubset(iterable): ReturnsTrueif all elements of the set are in the given iterable.issuperset(iterable): ReturnsTrueif all elements of the given iterable are in the set.isdisjoint(iterable): ReturnsTrueif the set and the given iterable have no elements in common (their intersection is empty).
set1 = {1, 2, 3}set2 = {3, 4, 5}result = set1.union(set2)print(result) # {1, 2, 3, 4, 5}
# Can also use the | operatorresult = set1 | set2 # {1, 2, 3, 4, 5}set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}result = set1.intersection(set2)print(result) # {3, 4}
# Can also use the & operatorresult = set1 & set2 # {3, 4}set1 = {1, 2, 3, 4, 5}set2 = {3, 4}result = set1.difference(set2)print(result) # {1, 2, 5}
# Can also use the - operatorresult = set1 - set2 # {1, 2, 5}set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}result = set1.symmetric_difference(set2)print(result) # {1, 2, 5, 6}
# Can also use the ^ operatorresult = set1 ^ set2 # {1, 2, 5, 6}set1 = {1, 2, 3}set2 = {1, 2, 3, 4, 5}print(set1.issubset(set2)) # True
# Can also use the <= operatorprint(set1 <= set2) # Trueset1 = {1, 2, 3, 4, 5}set2 = {1, 2, 3}print(set1.issuperset(set2)) # True
# Can also use the >= operatorprint(set1 >= set2) # Trueset1 = {1, 2, 3}set2 = {4, 5, 6}print(set1.isdisjoint(set2)) # True
set3 = {3, 4, 5}print(set1.isdisjoint(set3)) # False (they share element 3)Built-in Functions with Sets
Several built-in functions can be used with sets:
len(set): Returns the number of elements in the setmax(set): Returns the maximum elementmin(set): Returns the minimum elementsum(set): Returns the sum of all elements (if they are numeric)all(set): ReturnsTrueif all elements are truthyany(set): ReturnsTrueif any element is truthy
numbers = {1, 2, 3, 4, 5}
print(len(numbers)) # 5print(max(numbers)) # 5print(min(numbers)) # 1print(sum(numbers)) # 15print(all(numbers)) # Trueprint(any(numbers)) # TrueExercises
Exercise 1: Print all unique characters from a string
Write a program that reads a string and prints all the characters that appear in the string, each character only once (in the order they appear in the string).
Unique Characters
text = input()seen = set()for char in text: if char not in seen: seen.add(char) print(char)Exercise 2: Find characters that appear exactly once
Write a program that reads a string and prints all characters that appear exactly once in the string (in the order they first appear).
Characters Appearing Once
text = input()seen_once = set()seen_multiple = set()
for char in text: if char in seen_multiple: continue elif char in seen_once: seen_once.remove(char) seen_multiple.add(char) else: seen_once.add(char)
for char in text: if char in seen_once: print(char) seen_once.remove(char)Exercise 3: Find common elements between two sets
Write a program that reads the size of the first set, then reads its elements, then reads the size of the second set, then reads its elements, and prints the common elements (intersection) between the two sets.
Set Intersection
n1 = int(input())set1 = set()for i in range(n1): element = input() set1.add(element)
n2 = int(input())set2 = set()for i in range(n2): element = input() set2.add(element)
common = set1.intersection(set2)print(common)Exercise 4: Find elements in first set but not in second
Write a program that reads the size of the first set, then reads its elements, then reads the size of the second set, then reads its elements, and prints the elements that are in the first set but not in the second set (difference).
Set Difference
n1 = int(input())set1 = set()for i in range(n1): element = input() set1.add(element)
n2 = int(input())set2 = set()for i in range(n2): element = input() set2.add(element)
difference = set1.difference(set2)print(difference)Exercise 5: Union of two sets
Write a program that reads the size of the first set, then reads its elements, then reads the size of the second set, then reads its elements, and prints the union of both sets (all unique elements from both sets).
Set Union
n1 = int(input())set1 = set()for i in range(n1): element = input() set1.add(element)
n2 = int(input())set2 = set()for i in range(n2): element = input() set2.add(element)
union = set1.union(set2)print(union)Exercise 6: Remove duplicates from a list using a set
Write a program that reads the size of a list, then reads the elements, and creates a new list with all duplicates removed (preserving the order of first occurrence).
Remove Duplicates
n = int(input())original = []for i in range(n): original.append(input())
seen = set()result = []for item in original: if item not in seen: seen.add(item) result.append(item)
print(result)Exercise 7: Count unique elements in a list
Write a program that reads the size of a list, then reads the elements, and prints the count of unique elements.
Count Unique Elements
n = int(input())elements = []for i in range(n): elements.append(input())
unique = set(elements)print(len(unique))