Python Sets

In Python, a set is an unordered collection of unique elements. Unlike lists or tuples, sets do not store duplicate values and do not guarantee the order of elements. Sets are commonly used to perform operations like union, intersection, and set difference, making them powerful tools for mathematical and logical operations.

1. Creating a Set

You can create a set by placing elements inside curly braces {} or using the set() function. The elements in a set must be immutable, but the set itself is mutable.

Example:

# Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}

# Creating a set using the set() function
numbers = set([1, 2, 3, 4, 5])

# A set with mixed data types
mixed_set = {1, "apple", 3.14, True}

2. Accessing Set Elements

Since sets are unordered, you cannot access elements using an index like you do with lists or tuples. However, you can iterate over the set or use methods like in to check for membership.

Example:

fruits = {"apple", "banana", "cherry"}

# Checking if an element exists in a set
print("banana" in fruits)  # Output: True
print("orange" in fruits)  # Output: False

# Iterating through the set
for fruit in fruits:
    print(fruit)

3. Adding and Removing Elements

You can add elements to a set using the add() method, and you can remove elements using remove(), discard(), or pop().

  • add() adds an element to the set (only if it doesn’t already exist).
  • remove() removes an element from the set; if the element is not found, it raises a KeyError.
  • discard() removes an element if it exists; otherwise, it does nothing.
  • pop() removes and returns a random element from the set (sets are unordered, so it’s not predictable which element will be removed).

Example:

fruits = {"apple", "banana", "cherry"}

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

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

# Discarding an element (no error if the element is not found)
fruits.discard("grape")  # No effect, no error
print(fruits)  # Output: {'apple', 'cherry', 'orange'}

# Popping a random element
popped_element = fruits.pop()
print(fruits)  # Output: the set with one less element
print("Popped element:", popped_element)

4. Set Operations

Sets support various operations that are useful for mathematical set theory, including union, intersection, difference, and symmetric difference.

4.1. Union

The union of two sets returns a set that contains all the elements from both sets, excluding duplicates.

  • Union can be performed using the | operator or the union() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using the union() method
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5}

# Using the | operator
union_set = set1 | set2
print(union_set)  # Output: {1, 2, 3, 4, 5}

4.2. Intersection

The intersection of two sets returns a set containing only the elements that are present in both sets.

  • Intersection can be performed using the & operator or the intersection() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using the intersection() method
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {3}

# Using the & operator
intersection_set = set1 & set2
print(intersection_set)  # Output: {3}

4.3. Difference

The difference of two sets returns a set containing the elements that are in the first set but not in the second.

  • Difference can be performed using the - operator or the difference() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using the difference() method
difference_set = set1.difference(set2)
print(difference_set)  # Output: {1, 2}

# Using the - operator
difference_set = set1 - set2
print(difference_set)  # Output: {1, 2}

4.4. Symmetric Difference

The symmetric difference returns a set containing elements that are in either of the sets, but not in both.

  • Symmetric difference can be performed using the ^ operator or the symmetric_difference() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using the symmetric_difference() method
symmetric_diff_set = set1.symmetric_difference(set2)
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

# Using the ^ operator
symmetric_diff_set = set1 ^ set2
print(symmetric_diff_set)  # Output: {1, 2, 4, 5}

5. Set Subset and Superset

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

  • issubset() checks if all elements of a set are contained in another set.
  • issuperset() checks if a set contains all elements of another set.

Example:

set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Checking if set1 is a subset of set2
print(set1.issubset(set2))  # Output: True
print(set1 <= set2)  # Output: True

# Checking if set2 is a superset of set1
print(set2.issuperset(set1))  # Output: True
print(set2 >= set1)  # Output: True

6. Set Length

To find the number of elements in a set, you can use the len() function.

Example:

fruits = {"apple", "banana", "cherry"}
print(len(fruits))  # Output: 3

7. Set Methods

Python sets come with several built-in methods, such as:

MethodDescriptionExample
add()Adds an element to the setset.add(6)
remove()Removes an element (raises KeyError if not found)set.remove(2)
discard()Removes an element (does nothing if not found)set.discard(7)
pop()Removes a random elementset.pop()
clear()Removes all elements from the setset.clear()
union()Returns the union of two setsset1.union(set2)
intersection()Returns the intersection of two setsset1.intersection(set2)
difference()Returns the difference of two setsset1.difference(set2)
symmetric_difference()Returns the symmetric difference of two setsset1.symmetric_difference(set2)

8. Frozen Sets

A frozen set is an immutable version of a set. Once created, you cannot add or remove elements from a frozen set. You can create a frozen set using the frozenset() function.

Example:

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

# Trying to add or remove elements will raise an error
# frozen_fruits.add("orange")  # This will raise an AttributeError

Summary:

  • Sets are unordered collections of unique elements.
  • Sets support mathematical operations such as union, intersection, and difference.
  • You can add, remove, and check for membership in sets.
  • Sets are useful for eliminating duplicates and performing set-theoretic operations.
  • Frozen sets are immutable sets.
Leave a Reply 0

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