Sets are the guardians of uniqueness, ensuring each element stands out. Be like a set, stand out from the crowd!"
A set - is a mutable, unordered collection of items in Python
.
Every element is unique (no duplicates). and must be immutable (cannot be changed).
Sets can be created using curly braces {}
or the set()
function. However, an empty set can only be created using the set()
function, using {}
as it creates an empty dictionary
.
my_set = {1, 2, 3}
print(my_set)
print("Type is:", type(my_set))
empty_set = set()
print(empty_set)
print("Type of empty set is:", type(empty_set))
dictionary = {} # Be careful it is NOT a ``set``
print(dictionary)
print("Type is:", type(dictionary))
{1, 2, 3}
Type is: <class 'set'>
set()
Type of empty set is: <class 'set'>
{}
Type is: <class 'dict'>
Converting other iterables to sets can be useful for several reasons:
- Eliminating Duplicates:
Sets
automatically remove duplicate elements, which is useful for getting unique items. - Efficient Membership Testing: Checking whether an item exists in a
set
is faster compared tolists
ortuples
.
As for me, it is very underestimated data sctructure among py
devs' community, because based on my current experience I haven't seen many solutions where sets were used in production code.
The syntax for converting an iterable to a set involves the set()
constructor.
# Converting a list to a set
my_list = [1, 2, 3, 2, 1]
my_set = set(my_list)
print(my_set)
# Converting a tuple to a set
my_tuple = (4, 5, 6, 5, 4)
my_set = set(my_tuple)
print(my_set)
# Converting a string to a set
my_string = "hello"
my_set = set(my_string)
print(my_set)
{1, 2, 3}
{4, 5, 6}
{'e', 'h', 'l', 'o'}
Bear in mind that the order of elements in sets
can be different from time to time you output the elements.
Sets do NOT support indexing
or slicing
.
This sounds logically, as there is no order in how elements are stored and they can't be accessed by index.
my_set = {1, 2, 3}
# The following lines will raise an error
print(my_set[0])
print(my_set[0:2])
TypeError: 'set' object is not subscriptable
You can do various math operations with sets
in Python
.
Python's built-in functions like len()
, max()
, min()
, sum()
, and sorted()
can also be applied to sets.
# Define two sets
A = {1, 2, 3}
B = {3, 4, 5}
# Perform set operations
union = A | B # or A.union(B)
intersection = A & B # or A.intersection(B)
difference = A - B # or A.difference(B)
symmetric_difference = A ^ B # or A.symmetric_difference(B)
# Display the results
print("Union:", union)
print("Intersection:", intersection)
print("Difference:", difference)
print("Symmetric Difference:", symmetric_difference)
# Apply built-in functions
length = len(A)
max_value = max(A)
min_value = min(A)
sum_value = sum(A)
sorted_list = sorted(A) # Note: sorted() returns a list
# Display the results
print("Length:", length)
print("Max:", max_value)
print("Min:", min_value)
print("Sum:", sum_value)
print("Sorted:", sorted_list)
# Membership test
print("-" * 10)
print(1 in A)
print("A" in A)
Union: {1, 2, 3, 4, 5}
Intersection: {3}
Difference: {1, 2}
Symmetric Difference: {1, 2, 4, 5}
Length: 3
Max: 3
Min: 1
Sum: 6
Sorted: [1, 2, 3]
----------
True
False
Set comparison operators in Python enable you to compare sets based on their contents, allowing you to check for subset, superset, or equality relationships. These operations are particularly useful when dealing with collections of elements where the focus is on the presence or absence of items rather than their order or frequency.
- A subset (
<
) is a set where all its elements are contained within another set. - A superset (
>
) is a set that contains all elements of another set.
Python provides the <
, <=
, >
, and >=
operators, along with the methods .issubset()
, .issuperset()
for these comparisons.
- Two sets are considered equal (
==
) if they contain the same elements, regardless of their order.
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 3}
# Checking for subset
is_subset = A < B # or A.issubset(B)
print(f"A is a subset of B: {is_subset}")
# Checking for superset
is_superset = B > A # or B.issuperset(A)
print(f"B is a superset of A: {is_superset}")
# Checking for equality
is_equal = A == C
print(f"A is equal to C: {is_equal}")
# Using <= and >= for subset and superset including equality
is_subset_or_equal = A <= C
is_superset_or_equal = B >= C
print(f"A is a subset or equal to C: {is_subset_or_equal}")
print(f"B is a superset or equal to C: {is_superset_or_equal}")
# Non-equivalence
is_not_equal = B != C
print(f"B is not equal to C: {is_not_equal}")
A is a subset of B: True
B is a superset of A: True
A is equal to C: True
A is a subset or equal to C: True
B is a superset or equal to C: True
B is not equal to C: True
Python sets come with methods that allow you to modify set elements and compare sets in various ways.
Method | Description |
---|---|
add(element) |
Adds an element to the set. |
remove(element) |
Removes an element from the set. Raises a KeyError if the element is not present. |
discard(element) |
Removes an element from the set if it is a member. If the element is not a member, does nothing. |
pop() |
Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty. |
clear() |
Removes all elements from the set. |
Method | Description |
---|---|
union(*others) |
Returns a new set with elements from the set and all others. |
intersection(*others) |
Returns a new set with elements common to the set and all others. |
difference(*others) |
Returns a new set with elements in the set that are not in the others. |
symmetric_difference(other) |
Returns a new set with elements in either the set or other but not both. |
update(*others) |
Updates the set, adding elements from all others. |
intersection_update(*others) |
Updates the set, keeping only elements found in it and all others. |
difference_update(*others) |
Updates the set, removing elements found in others. |
symmetric_difference_update(other) |
Updates the set, keeping only elements found in either set, but not in both. |
A = {1, 2, 3}
B = {3, 4, 5}
# Add and remove elements
A.add(4)
A.discard(2)
print(f"After add and discard: {A}")
# Set operations
union_set = A.union(B)
intersection_set = A.intersection(B)
difference_set = A.difference(B)
print(f"Union: {union_set}")
print(f"Intersection: {intersection_set}")
print(f"Difference: {difference_set}")
After add and discard: {1, 3, 4}
Union: {1, 3, 4, 5}
Intersection: {3, 4}
Difference: {1}
Just like for list comprehensions, there is a support for set comprehensions as well.
# Create a set of squares using set comprehension
squares = {x**2 for x in range(10)}
print(squares)
# Create a set from a list where only even numbers are stored
evens = {x for x in range(10) if x % 2 == 0}
print(evens)
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}
{0, 2, 4, 6, 8}
A frozenset
is the immutable version of a set. Once created, items cannot be added or removed from a frozenset
.
This immutability makes frozenset
instances hashable, so they can be used as keys in dictionaries or as elements in other sets.
immutable_set = frozenset([1, 2, 3])
print(immutable_set)
# Attempt to add an element (This will raise an error)
try:
immutable_set.add(4)
except AttributeError as e:
print(e)
frozenset({1, 2, 3})
'frozenset' object has no attribute 'add'
What method would you use to add an element to a set in Python?
A) push()
B) append()
C) add()
D) insert()
Which set method is used to remove an element that might not be present in the set?
A) remove()
B) discard()
C) pop()
D) delete()
What will be the result of the following code snippet?
{1, 2, 3} & {2, 3, 4}
A) {2, 3}
B) {1, 2, 3, 4}
C) {1, 4}
D) TypeError
Which of the following is true for the
frozenset
type?
A) It is mutable.
B) It can contain mutable items.
C) It can be used as a dictionary key.
D) Elements can be added to it using add()
.
What does the union() method do when applied to two sets, A and B?
A) Finds elements that are in both A and B.
B) Creates a new set with elements from both A and B, excluding duplicates.
C) Removes from A all elements that are also in B.
D) Creates a new set with elements that are unique to each set.
How would you remove all elements from a set A in Python?
A) A.delete()
B) A.clear()
C) A.removeAll()
D) A.discardAll()
Given
A = {1, 2, 3}
andB = {3, 4, 5}
, what is the result ofA - B
?
A) {1, 2}
B) {3}
C) {4, 5}
D) {1, 2, 4, 5}
Which of the following will create a set containing the elements 1, 2, and 3?
A) set(1, 2, 3)
B) set([1, 2, 3])
C) {[1, 2, 3]}
D) {1: 'a', 2: 'b', 3: 'c'}
Objective:
- Create two sets,
A
andB
, whereA
contains numbers from 1 to 10 andB
contains numbers from 5 to 15. - Perform the following operations and print the results:
- Find the union of
A
andB
. - Find the intersection of
A
andB
. - Find the difference between
A
andB
. - Find the symmetric difference between
A
andB
. - Add a new element 16 to set
B
and remove element 5. - Check if
A
is a subset ofB
and vice versa.
Objective:
- Create three sets,
X
,Y
, andK
, with random numbers and some common elements among them. - Update set
X
with the intersection ofX
,Y
, andK
. - Perform a symmetric difference update between set
Y
and setK
. - Check if
X
is now a subset ofY
orK
and print the result. - Convert set
K
into an immutable set and attempt to add another element to demonstrate the immutable property.
Objective: Create a game where players guess letters of a secret word, using sets to track guessed letters and determine the game's progress.
## Example
Input: Secret Word: "banana", Guessed Letters: {'a', 'n'}, Guess: 'b'
Output: Correct
Input: Secret Word: "apple", Guessed Letters: {'a', 'e', 'p'}, Guess: 'c'
Output: Incorrect