Python: Sets
Python Sets
1 Overview
📘 Sets in Python
A set in Python is an unordered collection of unique elements, which means it cannot contain duplicate values. Sets are mutable, allowing for elements to be added or removed, but the elements themselves must be immutable types. Unlike lists or tuples, sets do not support indexing or slicing because they do not maintain any order among their elements.
2 Key characteristics of Python sets include:
- Unordered: The elements are stored without any particular sequence.
- Unique elements: Each element can appear only once in a set.
- Mutable container: The set itself can be modified by adding or removing elements.
- Elements must be hashable (immutable types such as numbers, strings, and tuples).
- Sets support standard mathematical set operations such as union, intersection, difference, and symmetric difference.
- Sets are commonly used for fast membership testing and eliminating duplicates from collections.
Python sets can be created using curly braces {} or the set() constructor, the latter being necessary for creating an empty set. They can be constructed from any iterable, allowing conversion from lists, tuples, or other collections.
Set manipulation methods include adding elements with add(), updating with multiple elements using update(), and removing elements with remove() or discard().
Overall, Python sets provide an efficient and convenient way to work with collections of distinct items with operations resembling those in mathematical set theory.
3 Sets
- Unordered collection of unique elements.
- E.g., useful for guaranteeing no duplicates.
4 Indexing Not Allowed
- Set elements are unordered, so we cannot access them using indices:
5 Mutability
setsare mutable.- To add elements to a set, use
add()method.
- To remove elements, use
remove()method.
- Multi-type:
- However, only immutable types are allowed inside sets!
- Convert sets to lists or tuples and vice versa.
- Take care: repeated elements from the list are removed when converting to a set.
[1, 2, 3]
(1, 2, 3)
6 in
- Like lists, check if an element is inside a set:
7 Operations
8 Union
9 Intersection
- With
&orintersection().
10 Difference
11 Symmetric difference
- With
^orsymmetric_difference().
12 Functions and methods
- Common built-in functions:
len(),sum(),max(), etc.
The sum of my_set is 6.
The max of my_set is 3.
- Other common methods:
issubset(),issuperset().
Is set3 a subset of set2? True
Is set2 a superset of set3? True
- More methods: https://www.w3schools.com/python/python_ref_set.asp.
13 Update
14 Iteration
- The same as lists and tuples:
2
3
15 Comprehension
- Similar to lists:
16 Example
Given a string, count the number of distinct words present in the string.
4
17 Exercises
17.1 Set operations
Given two sets, you can perform various operations to analyze their relationships. Each operation provides different insights into how the sets relate to one another. Given two sets, display their:
- Union combines all unique elements from both sets.
- Intersection finds elements that are present in both sets.
- Difference identifies elements that are in the first set but not in the second.
- Symmetric Difference includes elements that are in either of the sets but not in both.
Example 1
Input: set1 = {1, 2, 3, 4, 5}, set2 = {4, 5, 6, 7, 8}
Output: Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference: {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Example 2
Input: set1 = {10, 20, 30}, set2 = {30, 40, 50}
Output: Union: {10, 20, 30, 40, 50}
Intersection: {30}
Difference: {10, 20}
Symmetric Difference: {10, 20, 40, 50}
Example 3
Input: set1 = {1, 2}, set2 = {1, 2}
Output: Union: {1, 2}
Intersection: {1, 2}
Difference: set()
Symmetric Difference: set()
17.2 Membership
Given a set of integers and an element, check if the specified element is present in the set.
Example 1
Input: my_set = {1, 2, 3, 4, 5}
Input: element = 3
Output: True
Example 2
Input: my_set = {1, 2, 3, 4, 5}
Input: element = 6
Output: False
Example 3
Input: my_set = {‘apple’, ‘banana’, ‘cherry’}
Input: element = ‘banana’
Output: True
17.3 Sub and superset
Given two sets, determine if the first set is a subset of the second set, and simultaneously check if the second set is a superset of the first set. A set is considered a subset of another set if all elements of the first set are contained within the second set. Conversely, a set is a superset of another set if it contains all elements of the first set.
Example 1
Input: set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
Output: Set1 is a subset of Set2: True
Output: Set2 is a superset of Set1: True
Example 2
Input: set1 = {1, 2, 6}
set2 = {1, 2, 3, 4, 5}
Output: Set1 is a subset of Set2: False
Output: Set2 is a superset of Set1: False
17.4 Unique elements
Given a list of elements, the task is to create a new list that contains only the unique elements from the original list. Use the set data structure to easily solve this problem.
Example 1
Input: my_list = [1, 2, 3, 2, 1, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Example 2
Input: my_list = ['apple', 'banana', 'apple', 'orange', 'banana']
Output: ['apple', 'banana', 'orange']
Example 3
Input: my_list = [True, False, True, True]
Output: [True, False]
17.5 Attendance
You have attendance lists for 3 different courses. Find students who assisted all classes.
Example
Input:
math = [“Alice”, “Bob”, “Charlie”, “John”, “Eve”, “Abbott”]
physics = [“Bob”, “Eve”, “Charlie”, “David”, “Alice”, “Susan”]
cs = [“Charlie”, “Abbott”, “Bob”, “David”, “Eve”]
Output: {‘Charlie’, ‘Eve’, ‘Bob’}
17.6 Disjoint sets
Given two sets, determine if they are disjoint, meaning they have no elements in common.
Example 1
Input: set1 = {1, 2, 3}
set2 = {4, 5, 6}
Output: Set1 and Set2 are disjoint: True
Example 2
Input: set1 = {1, 2, 3}
set2 = {3, 4, 5}
Output: Set1 and Set2 are disjoint: False
Example 3
Input: set1 = {'a', 'b', 'c'}
set2 = {'d', 'e', 'f'}
Output: Set1 and Set2 are disjoint: True
Example 4
Input: set1 = {1, 2, 3}
set2 = {2, 3, 4}
Output: Set1 and Set2 are disjoint: False
17.7 Missing Numbers
You’re given an integer n and a list of numbers that should contain all elements from 0 to n, in no specific order. However, some values have been lost. Display the missing elements in ascending order.
Example
Input: n = 10; rng = [4, 8, 2, 1, 3, 9]
Output: [0, 5, 6, 7, 10]



