Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. Set and Frozenset in Python

Set and Frozenset in Python

A set in Python is an unordered collection of unique elements. This means no duplicates are allowed, and the order of elements is not preserved.

  • Sets are defined using curly braces {} or the set() function.
  • Sets are mutable, meaning you can add or remove elements after creation.
  • Sets do not support indexing or slicing because they are unordered.

1.) Accessing Elements::

Since sets are unordered, elements are accessed using loops.

Example:

s = {1, 2, 3}
for item in s:
    print(item)

2.) Adding Items:

Use the add() method to insert a new element.

Example:

s = {1, 2}
s.add(3)
print(s)    # Output: {1, 2, 3}

3.) Removing Items:

  • remove(item): Removes an element; raises error if not found.
  • discard(item): Removes an element; does not raise error if not found.

Example:

s = {1, 2, 3}
s.remove(2)
s.discard(5)  # No error even if 5 not in set
print(s)      # Output: {1, 3}

4.) Set Operations:

image 3

Example:

s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 | s2)  # Union: {1, 2, 3, 4, 5}
print(s1 & s2)  # Intersection: {3}
print(s1 - s2)  # Difference: {1, 2}

A frozenset is an immutable version of a set. Once created, its elements cannot be changed, i.e., you can’t add or remove items.

  • Created using the frozenset() function.
  • Useful when you need a set that should not be modified (e.g., for dictionary keys or as constants).

Example:

fs = frozenset([1, 2, 3])
print(fs)               # Output: frozenset({1, 2, 3})
# fs.add(4) will raise an error

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *