Sets in Python
Sets
62
A set in Python is a collection of unique elements. This means that no element in a set can occur more than once. Sets are mutable, which means their contents can be changed by adding, deleting, or updating elements.
In Python, sets are defined using curly braces { }
. Elements in a set are separated by commas.
Here's an example of defining a set:
my_set = {1, 2, 3, 3, 4, 5} print(my_set)
This will output: {1, 2, 3, 4, 5}
Notice how the duplicate element 3
was dropped from the set.
Sets also have a variety of built-in functions and methods.
Some of the most commonly used ones are:
len()
to find the length of a set
add()
to add an element to a set
remove()
to remove an element from a set
union()
to get the union of two sets
intersection()
to get the intersection of two sets
difference()
to get the difference between two sets
Here's an example of using some of these functions:
s1 = {1, 2, 3} s2 = {3, 4, 5} print(len(s1)) # output: 3 s1.add(4) print(s1) # output: {1, 2, 3, 4} s2.remove(4) print(s2) # output: {3, 5} s3 = s1.union(s2) print(s3) # output: {1, 2, 3, 4, 5} s4 = s1.intersection(s2) print(s4) # output: {3} s5 = s1.difference(s2) print(s5) # output: {1, 2, 4}
Sets are useful for a variety of tasks in Python, such as removing duplicates from a list, checking for membership of an element, and performing set operations like union and intersection.
March 25, 2023