SET

A set is an unordered collection of unique elements. The primary purpose of a set is to eliminate duplicates and provide a data structure for testing membership and performing common set operations such as union, intersection, difference, and symmetric difference. Sets are defined using curly braces {} or the set() constructor.

# Creating a set

my_set = {1, 2, 3, 3, 4, 5}

print(my_set)  # Output: {1, 2, 3, 4, 5}

 

# Sets automatically remove duplicate elements

another_set = {1, 2, 2, 3, 4, 4, 5}

print(another_set)  # Output: {1, 2, 3, 4, 5}

 

# Adding elements to a set

my_set.add(6)

print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

 

# Removing elements from a set

my_set.remove(3)

print(my_set)  # Output: {1, 2, 4, 5, 6}

 

# Set operations

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

 

# Union

union_set = set1 | set2  # or use set1.union(set2)

print(union_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8}

 

# Intersection

intersection_set = set1 & set2  # or use set1.intersection(set2)

print(intersection_set)  # Output: {4, 5}

 

# Difference

difference_set = set1 - set2  # or use set1.difference(set2)

print(difference_set)  # Output: {1, 2, 3}

 

# Symmetric Difference

symmetric_difference_set = set1 ^ set2  # or use set1.symmetric_difference(set2)

print(symmetric_difference_set)  # Output: {1, 2, 3, 6, 7, 8}