Sets in Python are unordered collections of unique elements. They provide a way to store and manipulate data without duplicate values. Sets are particularly useful when dealing with scenarios that require unique elements and performing set-based operations.


#Sets
print(set("my name is Eric and Eric is my name".split()))

a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b)

In Python, sets are defined by enclosing comma-separated elements within curly braces ({}) or using the set() constructor. Sets support a range of operations, including adding and removing elements, testing membership, and performing set operations like union, intersection, and difference.


#Intersection method
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.intersection(b))
print(b.intersection(a))

#Symmetric Difference
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

Sets offer efficient methods to perform unique element operations. By using set operations like intersection(), union(), and difference(), we can combine, merge, and compare sets to extract common elements, combine unique elements, or identify differences between sets.


#Difference Method
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.difference(b))
print(b.difference(a))

#Union Method
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])

print(a.union(b))

Sets provide several advantages, such as ensuring unique elements, fast membership testing, and efficient set operations. They are commonly used in scenarios involving data deduplication, membership checks, and mathematical set operations.

Sets Exercise Solution


#Code Completed
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]

A = set(a)
B = set(b)

print(A.difference(B))

Sets in Python offer a powerful and efficient way to work with unique elements and perform set-based operations. By leveraging sets and their operations, we can streamline our code, eliminate duplicates, and perform complex operations with ease.