Set

Learn about sets in Python.

Ali Berro

By Ali Berro

11 min read Section
From: Python Fundamentals: From Zero to Hero

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: False and 0 are treated as duplicates, as are True and 1

Creating a Set

Sets can be created using curly braces {} or the set() constructor:

# Using curly braces
numbers = {1, 2, 3, 4, 5}
empty_set = set()

When creating a set, duplicate values are automatically removed:

# Using set() constructor with an iterable
chars = 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) # True
print(10 in numbers) # False
print(2 not in numbers) # False

Looping 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 X=XSTX = X \cup S \cup T \cup \ldots.
  • intersection_update(iterable1, iterable2, ...): Keeps only elements that are common to the set and all given iterables X=XSTX = X \cap S \cap T \cap \ldots.
  • symmetric_difference_update(iterable): Keeps only elements that are in the set or in the iterable, but not in both X=XSX = X \triangle S.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers) # {1, 2, 3, 4}
numbers.add(2) # Adding duplicate has no effect
print(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 a KeyError.
  • 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 X=XST...X = X - S - T - ....
  • pop(): Removes and returns an arbitrary (random) element from the set. If the set is empty, it raises a KeyError.
  • 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 unchanged
print(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 XSTX \cup S \cup T \cup \ldots.
  • intersection(iterable1, iterable2, ...): Returns a new set containing only elements that are common to the set and all given iterables XSTX \cap S \cap T \cap \ldots.
  • difference(iterable1, iterable2, ...): Returns a new set containing elements that are in the set but not in any of the given iterables XST...X - S - T - ....
  • symmetric_difference(iterable): Returns a new set containing elements that are in either the set or the iterable, but not in both XSX \triangle S.
  • issubset(iterable): Returns True if all elements of the set are in the given iterable.
  • issuperset(iterable): Returns True if all elements of the given iterable are in the set.
  • isdisjoint(iterable): Returns True if the set and the given iterable have no elements in common (their intersection is empty).
union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result) # {1, 2, 3, 4, 5}
# Can also use the | operator
result = set1 | set2 # {1, 2, 3, 4, 5}
intersection
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1.intersection(set2)
print(result) # {3, 4}
# Can also use the & operator
result = set1 & set2 # {3, 4}
difference
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
result = set1.difference(set2)
print(result) # {1, 2, 5}
# Can also use the - operator
result = set1 - set2 # {1, 2, 5}
symmetric_difference
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 ^ operator
result = set1 ^ set2 # {1, 2, 5, 6}
issubset
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2)) # True
# Can also use the <= operator
print(set1 <= set2) # True
issuperset
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3}
print(set1.issuperset(set2)) # True
# Can also use the >= operator
print(set1 >= set2) # True
isdisjoint
set1 = {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 set
  • max(set): Returns the maximum element
  • min(set): Returns the minimum element
  • sum(set): Returns the sum of all elements (if they are numeric)
  • all(set): Returns True if all elements are truthy
  • any(set): Returns True if any element is truthy
numbers = {1, 2, 3, 4, 5}
print(len(numbers)) # 5
print(max(numbers)) # 5
print(min(numbers)) # 1
print(sum(numbers)) # 15
print(all(numbers)) # True
print(any(numbers)) # True

Exercises

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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
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

Checks: 0 times
Answer:
n = int(input())
elements = []
for i in range(n):
elements.append(input())
unique = set(elements)
print(len(unique))

Course Progress

Section 26 of 61

Back to Course