HomepythonSet and frozenset in Python

Set and frozenset in Python

Introduction

Sets in Python are unordered collections of unique elements. They are commonly used for membership testing, eliminating duplicate entries, and performing mathematical operations like union, intersection, and difference. Python provides two types of sets: set and frozenset. While set is mutable, allowing for modification after creation, frozenset is immutable and hashable, making it suitable for use as dictionary keys or elements of another set. This article explores the creation, manipulation, and methods associated with both set and frozenset.

What are Sets?

A set is a collection of unique, unordered elements. This means that no two elements can be the same and their order is not fixed.

Creating Sets

You can create a set using curly braces {} or the set() constructor.

# Using curly braces
fruits = {'apple', 'banana', 'cherry'}

# Using the set() constructor
numbers = set([1, 2, 3, 4, 5])

Adding Elements

You can add elements to a set using the add() method.

fruits.add('orange')
print(fruits)  # Output: {'apple', 'banana', 'cherry', 'orange'}

Removing Elements

Elements can be removed using remove(), discard(), pop(), and clear() methods.

fruits.remove('banana')  # Raises KeyError if 'banana' is not found
fruits.discard('grape')  # Does nothing if 'grape' is not found

# Removing and returning an arbitrary element
removed_element = fruits.pop()
print(removed_element)  # Outputs a random element from the set

# Removing all elements
fruits.clear()
print(fruits)  # Output: set()

What are Frozensets?

A frozenset is an immutable version of a set. Once created, the elements of a frozenset cannot be changed, making it hashable and eligible for use as dictionary keys or elements of another set.

Creating Frozensets

You can create a frozenset using the frozenset() constructor.

frozen_fruits = frozenset(['apple', 'banana', 'cherry'])
print(frozen_fruits)  # Output: frozenset({'apple', 'banana', 'cherry'})

Set Operations

Both sets and frozensets support a variety of operations. Here are the most common ones:

Union

The union of two sets is a set containing all unique elements from both sets.

a = {1, 2, 3}
b = {3, 4, 5}
union_set = a.union(b)
print(union_set)  # Output: {1, 2, 3, 4, 5}

Intersection

The intersection of two sets is a set containing only the elements present in both sets.

intersection_set = a.intersection(b)
print(intersection_set)  # Output: {3}

Difference

The difference of two sets is a set containing elements present in the first set but not in the second.

difference_set = a.difference(b)
print(difference_set)  # Output: {1, 2}

Symmetric Difference

The symmetric difference of two sets is a set containing elements present in either of the sets but not in both.

sym_diff_set = a.symmetric_difference(b)
print(sym_diff_set)  # Output: {1, 2, 4, 5}

Subset and Superset

You can check if a set is a subset or superset of another set using the issubset() and issuperset() methods.

x = {1, 2}
y = {1, 2, 3}
print(x.issubset(y))  # Output: True
print(y.issuperset(x))  # Output: True

Set Methods

Here are some useful methods available for sets:

add()

Adds an element to the set.

fruits.add('melon')

remove()

Removes a specified element from the set. Raises a KeyError if the element is not found.

fruits.remove('apple')

discard()

Removes a specified element from the set if it is present.

fruits.discard('banana')

pop()

Removes and returns an arbitrary element from the set.

random_fruit = fruits.pop()

clear()

Removes all elements from the set.

fruits.clear()

copy()

Returns a shallow copy of the set.

fruits_copy = fruits.copy()

union()

Returns the union of sets.

combined_set = fruits.union({'kiwi', 'grape'})

intersection()

Returns the intersection of sets.

common_elements = fruits.intersection({'banana', 'melon'})

difference()

Returns the difference of sets.

unique_elements = fruits.difference({'apple', 'grape'})

symmetric_difference()

Returns the symmetric difference of sets.

sym_diff = fruits.symmetric_difference({'apple', 'melon'})

Frozenset Methods

Frozensets support most of the set methods, except for those that modify the set (like add(), remove(), discard(), pop(), and clear()). The methods available for frozensets include:

  • copy()
  • union()
  • intersection()
  • difference()
  • symmetric_difference()
  • issubset()
  • issuperset()

Sets and frozensets in Python are powerful tools for handling collections of unique elements. While sets offer flexibility with their mutability, frozensets provide the immutability required for certain use cases like dictionary keys.

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular