Python set
Created By: chatGPT
Sets in Python are a built-in data structure that allows you to store unique values. They are useful when you need to keep collections of items without duplicates. A set is unordered, meaning the items do not maintain a specific order. Sets can be created using curly braces
{}
or the set()
constructor.my_set = {1, 2, 3, 4, 5}
# Creating a set with the set() constructor
my_set2 = set([1, 2, 3, 4, 5])
You can perform various operations on sets, such as union, intersection, and difference. These operations can be performed using methods or operators.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Union
union_set = set_a | set_b # {1, 2, 3, 4, 5}
# Intersection
intersection_set = set_a & set_b # {3}
# Difference
difference_set = set_a - set_b # {1, 2}
You can also add or remove elements from a set using specific methods. Use
add()
to add a single element and update()
to add multiple elements. To remove elements, use remove()
or discard()
.my_set.add(6) # Add a single element
my_set.update([7, 8]) # Add multiple elements
my_set.remove(4) # Removes 4, raises KeyError if not found
my_set.discard(4) # Removes 4 but does not raise an error if not found
You can also check membership in a set using the
in
operator, which is an efficient way to check if an item exists in a set.if 3 in my_set:
print('3 is in the set!')
if 10 not in my_set:
print('10 is not in the set!')
Sets also support frozen sets, which are immutable versions of regular sets. Once created, frozen sets cannot be modified.
frozen_set = frozenset([1, 2, 3])
# Immutable, following operations will raise error:
# frozen_set.add(4) # AttributeError