878959. Implement Set in Python

Easy

Here is the detailed Markdown blog post for the problem "Implement Set in Python":

Implement Set in Python

Summary

Create a set data structure in Python, allowing users to add unique elements and check if an element exists. This problem focuses on implementing basic set operations such as union, intersection, and difference.

Detailed Explanation

To implement a set in Python, we will use the built-in set data type. A set is an unordered collection of unique elements. We can create a set by passing a list or tuple to the set() function. For example: my_set = set([1, 2, 3]). Sets support various operations like union (|), intersection (&), and difference (-).

Here's how we can implement these operations:

  • Union: The union of two sets is the set of elements which are in either of the sets. We can use the | operator to find the union.

    my_set1 = {1, 2, 3}
    my_set2 = {4, 5, 6}
    
    union_set = my_set1 | my_set2
    print(union_set)  # Output: {1, 2, 3, 4, 5, 6}
    
  • Intersection: The intersection of two sets is the set of elements which are in both sets. We can use the & operator to find the intersection.

    my_set1 = {1, 2, 3}
    my_set2 = {4, 5, 6}
    
    intersection_set = my_set1 & my_set2
    print(intersection_set)  # Output: set()
    
  • Difference: The difference of two sets is the set of elements which are in the first set but not in the second. We can use the - operator to find the difference.

    my_set1 = {1, 2, 3}
    my_set2 = {4, 5, 6}
    
    difference_set = my_set1 - my_set2
    print(difference_set)  # Output: {1, 2, 3}
    

Optimized Solutions

Python

python
class Set:
    def __init__(self):
        self.my_set = set()

    def add(self, item):
        self.my_set.add(item)

    def union(self, other_set):
        return self.my_set.union(other_set.my_set)

    def intersection(self, other_set):
        return self.my_set.intersection(other_set.my_set)

    def difference(self, other_set):
        return self.my_set.difference(other_set.my_set)


# Example usage:
my_set1 = Set()
my_set1.add(1)
my_set1.add(2)
my_set1.add(3)

my_set2 = Set()
my_set2.add(4)
my_set2.add(5)
my_set2.add(6)

print(my_set1.union(my_set2))  # Output: {1, 2, 3, 4, 5, 6}
print(my_set1.intersection(my_set2))  # Output: set()
print(my_set1.difference(my_set2))  # Output: {1, 2, 3}

Note: The above code is just a basic implementation and does not handle duplicate values or edge cases. For real-world usage, consider using Python's built-in set data type.

View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.