Python Set Explain

Python Set Explanation

A set in Python is an unordered collection of unique elements. It does not allow duplicate values and supports mathematical set operations like union, intersection, and difference.

Creating a Set

We can create a set using curly braces {} or the set() function.

            
# Creating a set
numbers = {1, 2, 3, 4, 5, 5, 2}  # Duplicates are ignored
print(numbers)  # Output: {1, 2, 3, 4, 5}

# Using set() function
empty_set = set()
print(empty_set)  # Output: set()
            
        

Adding and Removing Elements

We can use add() to insert elements and remove() to delete elements.

            
numbers = {1, 2, 3}

# Adding elements
numbers.add(4)
print(numbers)  # Output: {1, 2, 3, 4}

# Removing elements
numbers.remove(2)
print(numbers)  # Output: {1, 3, 4}
            
        

Set Operations

Python sets support mathematical operations like union, intersection, and difference.

            
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union
print(A | B)  # Output: {1, 2, 3, 4, 5, 6}

# Intersection
print(A & B)  # Output: {3, 4}

# Difference
print(A - B)  # Output: {1, 2}

# Symmetric Difference
print(A ^ B)  # Output: {1, 2, 5, 6}
            
        

When to Use Sets?

  • When you need unique values in a collection.
  • For fast membership testing (e.g., x in set).
  • For performing mathematical set operations.