w3resource

Python Sets and Frozensets: Detailed Explanation and Use-Cases

Introduction to Python Sets and Frozensets

Sets and frozensets in Python are powerful data structures used for storing unique elements. While sets are mutable, frozensets are immutable. This tutorial will explore these data structures through practical examples with descriptions and explanations, focusing on their use-cases and functionality.

Introduction to Sets:

Sets are unordered collections of unique elements. They are mutable, meaning you can add or remove elements after creation.

Example 1: Creating and Using Sets

This example shows how to create a set, add elements to it, and remove elements from it.

Code:

# Creating a set of unique numbers
numbers = {1, 2, 3, 4, 5, 5, 4}  # Duplicate values will be removed

# Print the set
print(numbers)   

# Adding an element to the set
numbers.add(6)

# Print the set after adding an element
print(numbers)   

# Removing an element from the set
numbers.remove(3)

# Print the set after removing an element
print(numbers) 

Output:

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}

Explanation:

Sets automatically remove duplicate values, as seen when '{1, 2, 3, 4, 5, 5, 4}' becomes '{1, 2, 3, 4, 5}'. You can add elements using '.add()' and remove elements using '.remove()'. Sets are useful for situations where you need to ensure all elements are unique.

Basic Set Operations:

Sets support standard operations like union, intersection, difference, and symmetric difference, which are useful for comparing collections.

Example 2: Set Operations

This example demonstrates common set operations: union, intersection, difference, and symmetric difference.

Code:

# Create two sets
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# Union of sets (all unique elements from both sets)
union = set_a | set_b
print(union)  # Output: {1, 2, 3, 4, 5, 6}

# Intersection of sets (common elements)
intersection = set_a & set_b
print(intersection)  # Output: {3, 4}

# Difference of sets (elements in set_a but not in set_b)
difference = set_a - set_b
print(difference)  # Output: {1, 2}

# Symmetric difference (elements in either set_a or set_b but not both)
sym_diff = set_a ^ set_b
print(sym_diff)  # Output: {1, 2, 5, 6}  

Output:

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{1, 2, 5, 6}

Explanation:

  • Union (|) combines all unique elements from both sets.
  • Intersection (&) finds elements common to both sets.
  • Difference (-) finds elements in one set but not the other.
  • Symmetric difference (^) finds elements in either set, but not in both.

Checking Membership and Subsets:

Sets provide efficient methods for checking membership, subsets, and supersets.

Example 3: Membership and Subset Operations

This example shows how to check if an element is in a set, and how to check subset and superset relationships between sets.

Code:

# Create a set
set_c = {1, 2, 3, 4, 5}

# Check if an element is in the set
print(3 in set_c)  # Output: True

# Check if a set is a subset of another set
subset = {1, 2}
print(subset.issubset(set_c))  # Output: True

# Check if a set is a superset of another set
print(set_c.issuperset(subset))  # Output: True

Output:

True
True
True

Explanation:

  • Membership (in) checks if an element is present in a set.
  • Subset (issubset()) checks if all elements of one set are contained in another set.
  • Superset (issuperset()) checks if a set contains all elements of another set.

Introduction to Frozensets:

Frozensets are immutable sets, meaning their elements cannot be modified after creation. They are useful when a set needs to be a key in a dictionary or an element of another set.

Example 4: Creating and Using Frozensets

This example demonstrates how to create a frozenset and the immutability of frozensets.

Code:

# Creating a frozenset
frozen_set = frozenset([1, 2, 3, 4, 5])

# Print the frozenset
print(frozen_set)  # Output: frozenset({1, 2, 3, 4, 5})

# Attempting to add or remove elements will raise an error
# frozen_set.add(6)  # AttributeError: 'frozenset' object has no attribute 'add'

Output:

frozenset({1, 2, 3, 4, 5})

Explanation:

A frozenset is created using ‘frozenset()’, making it immutable and hashable. Because of its immutability, you cannot add or remove elements once it’s created. This makes frozensets suitable for use as keys in dictionaries or for ensuring a collection of items remains unchanged.

Use-Case: Removing Duplicates from a List

One common use of sets is to remove duplicates from a list, as sets inherently store only unique items.

Example 5: Removing Duplicates

This example shows how to remove duplicates from a list using a set.

Code:

# A list with duplicate values
items = [1, 2, 2, 3, 4, 4, 5]

# Convert the list to a set to remove duplicates
unique_items = set(items)

# Print the set of unique items
print(unique_items)  # Output: {1, 2, 3, 4, 5} 

Output:

{1, 2, 3, 4, 5}

Explanation:

By converting a list to a set, all duplicate elements are automatically removed. This is an efficient way to ensure uniqueness in a collection of items.

Use-Case: Set Operations in Data Analysis

Sets are useful in data analysis for operations like finding common elements or differences between datasets.

Example 6: Finding Common Elements

This example demonstrates finding common elements between two sets, which is useful in data comparison tasks.

Code:

# Two lists of items (e.g., purchased products)
color_2023 = {'red', 'green', 'blue', 'white'}
color_2024 = {'green', 'pink', 'blue', 'orange'}
# Find common products purchased in both years
common_colors = color_2023 & color_2024
# Print the common products
print(common_colors)

Output:

{'green', 'blue'}

Explanation:

Using the intersection operator (&), you can quickly find elements that appear in both sets. This is particularly useful in data analysis when comparing different datasets for colors.

Use-Case: Set Comprehensions

Set comprehensions allow for the creation of sets from iterables in a concise and readable way, similar to list comprehensions.

Example 7: Set Comprehension

This example shows how to use set comprehensions to create a set of squares of even numbers.

Code:

# Create a set of squares for even numbers
even_squares = {x**2 for x in range(10) if x % 2 == 0}

# Print the set of even squares
print(even_squares)

Output:

{0, 64, 4, 36, 16}

Explanation:

Set comprehensions allow you to define sets in a single line with conditions. The set comprehension iterates over numbers from 0 to 9, squares them, and includes only the even numbers in the final set.



Become a Patron!

Follow us on Facebook and Twitter for latest update.