Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sets and Frozenset in Python

1. Introduction

In Python, a set is an unordered collection of unique elements. This lesson will cover the properties of sets and frozensets, which are immutable sets.

2. Sets

Sets are defined using curly braces or the set() constructor. Key properties include:

  • Unordered: Elements do not have a defined order.
  • Unique: Duplicate elements are not allowed.
  • Mutable: Elements can be added or removed.

Creating a Set

my_set = {1, 2, 3, 4}
print(my_set)  # Output: {1, 2, 3, 4}

Common Set Operations

  • add(element) - Adds an element to the set.
  • remove(element) - Removes an element; raises KeyError if not found.
  • discard(element) - Removes an element without raising an error if not found.
  • clear() - Removes all elements.

Example

my_set.add(5)
print(my_set)  # Output: {1, 2, 3, 4, 5}

my_set.discard(3)
print(my_set)  # Output: {1, 2, 4, 5}

3. Frozenset

A frozenset is an immutable version of a set. Once created, you cannot modify its elements.

Creating a Frozenset

my_frozenset = frozenset([1, 2, 3, 4])
print(my_frozenset)  # Output: frozenset({1, 2, 3, 4})

Important Note

A frozenset can be used as a key in a dictionary or an element in another set.

4. Comparison between Sets and Frozensets

Property Set Frozenset
Mutability Mutable Immutable
Hashable No Yes
Usage General use As dictionary keys or elements in other sets

5. Best Practices

  • Use sets to eliminate duplicate entries from a list.
  • Prefer frozensets when you need a constant collection of items.
  • Use set operations for efficient membership testing and mathematical operations.

6. FAQ

What happens if I try to add an element to a frozenset?

It will raise an AttributeError because frozensets are immutable.

Can sets contain mutable objects?

Yes, but only if the objects themselves do not change (e.g., lists cannot be added to a set).

How can I convert a list to a set?

Use the set() constructor: my_set = set(my_list).