Python Sets

A set is a collection of unique, unordered items. Python sets are used to store multiple elements in a single variable without duplicates. Sets are highly optimized for membership testing and removing duplicate entries from a sequence. Sets are written using curly braces {}.

Definition and Characteristics of Sets

Let's see how to create a basic set in Python:

Example 1: Creating a Set


# Example: Creating a Set
my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)
            

Output

Set: {1, 2, 3, 4, 5}

Sets can contain elements of different data types, including integers, strings, and floats:

Example 2: Set with Mixed Data Types


# Example: Set with Mixed Data Types
mixed_set = {1, "apple", 3.14, True}
print("Mixed Set:", mixed_set)
            

Output

Mixed Set: {1, 'apple', 3.14}

Note that the output does not show True as 1 because sets do not allow duplicate values, and True is treated as 1 in Python.

Basic Set Operations

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

Let's see how to perform these operations:

Example 3: Set Operations


# Example: Set Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union
print("Union:", A | B)

# Intersection
print("Intersection:", A & B)

# Difference
print("Difference:", A - B)

# Symmetric Difference
print("Symmetric Difference:", A ^ B)
            

Output

Union: {1, 2, 3, 4, 5, 6} Intersection: {3, 4} Difference: {1, 2} Symmetric Difference: {1, 2, 5, 6}

Explanation:
- Union (|): Combines elements from both sets, excluding duplicates.
- Intersection (&): Returns only elements found in both sets.
- Difference (-): Elements present in the first set but not in the second.
- Symmetric Difference (^): Elements in either set but not in both.

Common Set Methods

Python sets provide several built-in methods:

Here are some examples of using these methods:

Example 4: Using Set Methods


# Example: Using Set Methods
fruits = {"apple", "banana", "cherry"}

# Add an item
fruits.add("orange")
print("After add:", fruits)

# Remove an item
fruits.remove("banana")
print("After remove:", fruits)

# Discard an item (no error if not found)
fruits.discard("pineapple")
print("After discard:", fruits)

# Pop an item
item = fruits.pop()
print("Popped item:", item)
print("Set after pop:", fruits)

# Clear the set
fruits.clear()
print("After clear:", fruits)
            

Output

After add: {'apple', 'banana', 'cherry', 'orange'} After remove: {'apple', 'cherry', 'orange'} After discard: {'apple', 'cherry', 'orange'} Popped item: apple Set after pop: {'cherry', 'orange'} After clear: set()

Frozen Sets

Frozen sets are immutable versions of Python sets. Once a frozen set is created, you cannot modify it (i.e., no adding or removing elements). Frozen sets are useful when you need a constant set that remains unchanged.

Here’s an example of how frozen sets work:

Example 5: Frozen Sets


# Example: Creating a Frozen Set
frozen_set = frozenset([1, 2, 3, 4, 5])
print("Frozen Set:", frozen_set)

# Trying to add an element to a frozen set (will raise an error)
try:
    frozen_set.add(6)
except AttributeError as e:
    print("Error:", e)
            

Output

Frozen Set: frozenset({1, 2, 3, 4, 5}) Error: 'frozenset' object has no attribute 'add'