Python Sets
Sets are a data type in Python that store unique elements in no particular order. Sets are created with curly braces {}
or with the set()
constructor.
Syntax
# Creating a set
set1 = {1, 2, 3, 4, 5}
# Adding elements to a set
set1.add(6)
# Removing elements from a set
set1.remove(3)
# Intersection of two sets
set2 = {4, 5, 6, 7, 8}
set3 = set1.intersection(set2)
# Union of two sets
set4 = set1.union(set2)
# Difference of two sets
set5 = set1.difference(set2)
Example
# Create a set
set1 = {1, 2, 3, 4, 5}
# Print the set
print(set1)
# Add an element to the set
set1.add(6)
# Print the updated set
print(set1)
# Remove an element from the set
set1.remove(3)
# Print the updated set
print(set1)
# Intersection of two sets
set2 = {4, 5, 6, 7, 8}
set3 = set1.intersection(set2)
# Print the intersection set
print(set3)
# Union of two sets
set4 = set1.union(set2)
# Print the union set
print(set4)
# Difference of two sets
set5 = set1.difference(set2)
# Print the difference set
print(set5)
Output
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}
{4, 5}
{1, 2, 4, 5, 6, 7, 8}
{1, 2, 6}
Explanation
- We create a set
set1
with five elements. - We add an element
6
to the setset1
using theadd()
method. - We remove the element
3
from the setset1
using theremove()
method. - We find the intersection of
set1
andset2
using theintersection()
method and store the result inset3
. - We find the union of
set1
andset2
using theunion()
method and store the result inset4
. - We find the difference of
set1
andset2
using thedifference()
method and store the result inset5
.
Use
Sets can be used to store unique elements and perform operations such as intersection, union, and difference on them. They are also useful for checking if an element is present in a collection.
Important Points
- Sets are mutable, meaning they can be changed after they are created.
- Sets do not allow duplicate values.
- Set elements are not ordered, meaning they may appear in a different order when printed or iterated over.
- The
add()
method adds a single element to a set, while theupdate()
method can be used to add multiple elements at once. - The
remove()
method removes a single element from a set, while thediscard()
method removes an element if it is present, but does not raise an error if it is not. - The
union()
,intersection()
, anddifference()
methods return new sets without modifying the original sets.
Summary
Sets are a useful data type in Python for storing unique elements and performing operations such as intersection, union, and difference. They are created using curly braces or the set()
constructor, and offer methods for adding, removing, and manipulating elements. Sets do not allow duplicate values and are not ordered.