Python Sets


Sets in Python

A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add and remove elements, but every element must be unique (no duplicates are allowed). Sets are used when you want to store distinct items and perform operations like union, intersection, and difference.

Key Features of Sets:

  1. Unordered: Sets do not maintain the order of elements.
  2. Unique Elements: All elements in a set must be unique. If you add a duplicate, it will be automatically removed.
  3. Mutable: You can add or remove elements from a set.
  4. Unindexed: Since sets are unordered, you cannot access elements by index.

Set Syntax:

Sets are defined using curly braces {} or the set() function.

# Creating a set my_set = {1, 2, 3, 4} # Creating an empty set (must use set(), not {}) empty_set = set()

Example: Creating and Printing a Set

# Defining a set fruits = {"apple", "banana", "cherry", "apple"} print(fruits) # Output: {'banana', 'cherry', 'apple'} (duplicates removed)

Adding Elements to a Set:

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

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

Removing Elements from a Set:

Elements can be removed using the remove() or discard() methods. The difference is that remove() will raise an error if the element is not found, while discard() will not.

# Removing an element fruits.remove("banana") print(fruits) # Output: {'cherry', 'orange', 'apple'} # Using discard (won't raise an error if element not found) fruits.discard("pineapple")

You can also remove and return an arbitrary element using pop(), and remove all elements using clear().

# Using pop() to remove and return an arbitrary element item = fruits.pop() print(item) # Output: (one of the elements) print(fruits) # Using clear() to remove all elements fruits.clear() print(fruits) # Output: set()

Set Operations:

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

  1. Union (|): Combines all elements from two sets (removes duplicates).
set1 = {1, 2, 3} set2 = {3, 4, 5} # Union of sets union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5}
  1. Intersection (&): Returns only the elements common to both sets.
# Intersection of sets intersection_set = set1 & set2 print(intersection_set) # Output: {3}
  1. Difference (-): Returns the elements that are in the first set but not in the second.
# Difference of sets difference_set = set1 - set2 print(difference_set) # Output: {1, 2}
  1. Symmetric Difference (^): Returns elements that are in either of the sets but not in both.
# Symmetric difference of sets symmetric_diff_set = set1 ^ set2 print(symmetric_diff_set) # Output: {1, 2, 4, 5}

Set Methods:

  • add(x): Adds an element x to the set.
  • remove(x): Removes x from the set (raises an error if x is not in the set).
  • discard(x): Removes x from the set (does nothing if x is not in the set).
  • pop(): Removes and returns an arbitrary element from the set.
  • clear(): Removes all elements from the set.
  • union(set): Returns a new set containing all elements from both sets.
  • intersection(set): Returns a new set containing elements common to both sets.
  • difference(set): Returns a new set with elements from the first set that are not in the second set.
  • symmetric_difference(set): Returns a new set with elements that are in either set, but not both.
# Set methods set1.add(6) print(set1) # Output: {1, 2, 3, 6} set1.discard(2) print(set1) # Output: {1, 3, 6}

Set Comprehension:

You can create sets using set comprehension, similar to list comprehension.

# Example of set comprehension squared_set = {x**2 for x in range(1, 6)} print(squared_set) # Output: {1, 4, 9, 16, 25}

Checking Membership:

You can check if an element exists in a set using the in keyword.

# Checking membership in a set print(3 in set1) # Output: True print(10 in set1) # Output: False

Frozen Sets:

A frozenset is an immutable version of a set. Once a frozenset is created, you cannot add or remove elements from it. Frozensets are useful when you need an immutable set, such as using sets as keys in a dictionary.

# Creating a frozenset frozen_set = frozenset([1, 2, 3, 4]) print(frozen_set) # Output: frozenset({1, 2, 3, 4}) # Trying to add an element will raise an error # frozen_set.add(5) # AttributeError: 'frozenset' object has no attribute 'add'

Summary:

  • Sets are unordered collections of unique elements, used when you need to store distinct items.
  • They support set operations like union, intersection, and difference.
  • Frozen sets are immutable sets that cannot be modified once created.