Sets in Python
Sets are an unordered collection of unique elements in Python. They are defined using curly braces {}
or the set()
function.
Creating a Set
You can create a set by placing a comma-separated list of elements within curly braces or by using the set()
function.
# Creating sets
set1 = {1, 2, 3}
set2 = set([4, 5, 6])
Set Operations
Sets support various operations like union, intersection, difference, and symmetric difference.
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union
set_union = set_a | set_b # Output: {1, 2, 3, 4, 5, 6}
# Intersection
set_intersection = set_a & set_b # Output: {3, 4}
# Difference
set_difference = set_a - set_b # Output: {1, 2}
# Symmetric Difference
set_sym_difference = set_a ^ set_b # Output: {1, 2, 5, 6}
Adding and Removing Elements
You can add elements to a set using the add()
method and remove elements using the remove()
or discard()
methods.
# Adding and removing elements
my_set = {1, 2, 3}
# Add an element
my_set.add(4) # Output: {1, 2, 3, 4}
# Remove an element
my_set.remove(3) # Output: {1, 2, 4}
# Discard an element
my_set.discard(2) # Output: {1, 4}