Python Sets

Carson West

Python 1 Home

Python Sets

Python sets are unordered collections of unique elements. They are defined using curly braces {} or the set() constructor.

my_set = {1, 2, 3, 3, 4}  # Duplicates are automatically removed
print(my_set)  # Output: {1, 2, 3, 4}

another_set = set(5, 6, 7) # Creating a set from a list
print(another_set) # Output: {5, 6, 7}

empty_set = set() #Creating an empty set.  Note: {} creates an empty dictionary.
print(empty_set) #Output: set()

Key Set Operations:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) #or set1 | set2
print(union_set)  # Output: {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2) #or set1 & set2
print(intersection_set)  # Output: {3}
difference_set = set1.difference(set2) #or set1 - set2
print(difference_set)  # Output: {1, 2}
symmetric_difference_set = set1.symmetric_difference(set2) #or set1 ^ set2
print(symmetric_difference_set)  # Output: {1, 2, 4, 5}
my_set.add(5)
print(my_set)

Frozen Sets Python Sets - Examples

Set Comprehension: Similar to List Comprehension, but creates a set.

squares = {x**2 for x in range(5)}
print(squares)  # Output: {0, 1, 4, 9, 16}