4.3 Sets: Unordered Collections

Sets in Python are unordered collections of unique elements. Unlike lists and tuples, sets do not allow duplicate elements, and the order of items is not maintained. Sets are highly efficient for membership testing (i.e., checking if an element is in the set) and operations like unions, intersections, and differences, which are commonly used in mathematical and set theory operations.

In this section, we will explore how to create sets, add and remove elements, and perform common set operations.


4.3.1 Creating Sets

You can create a set by placing elements inside curly braces {} or by using the set() function. Elements in a set must be immutable, meaning you can include numbers, strings, and tuples, but not lists or other sets.

Syntax:

my_set = {element1, element2, element3, ...}
# OR
my_set = set(iterable)

Examples:

Creating a set from a list (duplicates are automatically removed):

my_list = [1, 2, 2, 3, 4]
my_set = set(my_list)
print(my_set)  # Output: {1, 2, 3, 4}

Creating an empty set:

empty_set = set()  # Cannot use {} as it creates an empty dictionary

A set of mixed types:

mixed_set = {1, "hello", 3.14}

A set of integers:

numbers = {1, 2, 3, 4, 5}

4.3.2 Accessing Set Elements

Since sets are unordered, you cannot access elements by index or perform slicing like in lists or tuples. However, you can iterate through a set using a for loop.

Example:

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

for fruit in fruits:
    print(fruit)

Output (order may vary):

apple
banana
cherry

4.3.3 Adding and Removing Elements

Sets are mutable, meaning you can add or remove elements from them.

4.3.3.1 Adding Elements

You can add elements to a set using the add() method. If the element is already in the set, no changes will be made since sets only contain unique elements.

Example:

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

4.3.3.2 Removing Elements

You can remove elements using the remove() or discard() methods:

  • remove(element) raises a KeyError if the element is not found.
  • discard(element) does not raise an error if the element is not found.

Example with remove():

fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # Output: {'apple', 'cherry'}

Example with discard():

fruits.discard("banana")  # No error even if "banana" is already removed

4.3.3.3 Clearing the Set

You can remove all elements from a set using the clear() method.

Example:

fruits.clear()
print(fruits)  # Output: set()

4.3.4 Set Operations

Python provides a variety of operations that are commonly used in set theory, such as unions, intersections, differences, and symmetric differences. These operations can be performed using operators or corresponding methods.

4.3.4.1 Union

The union of two sets contains all elements that are in either set. This can be done using the | operator or the union() method.

Example:

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

4.3.4.2 Intersection

The intersection of two sets contains only the elements that are in both sets. This can be done using the & operator or the intersection() method.

Example:

intersection_set = set1 & set2  # OR set1.intersection(set2)
print(intersection_set)  # Output: {3}

4.3.4.3 Difference

The difference of two sets contains the elements that are in the first set but not in the second. This can be done using the - operator or the difference() method.

Example:

difference_set = set1 - set2  # OR set1.difference(set2)
print(difference_set)  # Output: {1, 2}

4.3.4.4 Symmetric Difference

The symmetric difference contains elements that are in either set, but not in both. This can be done using the ^ operator or the symmetric_difference() method.

Example:

symmetric_difference_set = set1 ^ set2  # OR set1.symmetric_difference(set2)
print(symmetric_difference_set)  # Output: {1, 2, 4, 5}

4.3.5 Set Methods

Here are some commonly used set methods:

  1. add(element): Adds an element to the set.
  2. remove(element): Removes the element from the set, raises a KeyError if the element is not found.
  3. discard(element): Removes the element from the set, but does not raise an error if the element is not found.
  4. clear(): Removes all elements from the set.
  5. union(set): Returns the union of the sets.
  6. intersection(set): Returns the intersection of the sets.
  7. difference(set): Returns the difference between the sets.
  8. symmetric_difference(set): Returns the symmetric difference between the sets.
  9. isdisjoint(set): Returns True if the two sets have no elements in common.
  10. issubset(set): Returns True if all elements of the first set are in the second set.
  11. issuperset(set): Returns True if all elements of the second set are in the first set.

Examples:

issuperset():

print(set2.issuperset(set1))  # Output: True

issubset():

set1 = {1, 2}
set2 = {1, 2, 3, 4}
print(set1.issubset(set2))  # Output: True

isdisjoint():

set1 = {1, 2, 3}
set2 = {4, 5, 6}
print(set1.isdisjoint(set2))  # Output: True (no common elements)

4.3.6 Frozensets: Immutable Sets

A frozenset is an immutable version of a set, meaning you cannot modify its elements after creation. Frozensets are useful when you need to create a set that you want to keep constant throughout the program.

Syntax:

my_frozenset = frozenset(iterable)

Example:

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

# my_frozenset.add(5)  # Raises AttributeError: 'frozenset' object has no attribute 'add'

Frozensets support all set operations (union(), intersection(), etc.), but they do not support methods that modify the set (add(), remove(), etc.).


4.3.7 Use Cases for Sets

Membership Testing:
Sets provide an efficient way to test for the presence of an element, making them ideal for membership testing.Example:

fruits = {"apple", "banana", "cherry"}
print("apple" in fruits)  # Output: True
print("grape" in fruits)  #

Removing Duplicates from a List:
Since sets automatically remove duplicates, they are useful when you need to filter out duplicate elements from a list.Example:

my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)
print(unique_set)  # Output: {1, 2, 3, 4, 5}

Output: False


3. **Mathematical Set Operations**:
Sets are ideal for performing mathematical operations like unions, intersections, and differences.

Example (union):
```python
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a | set_b)  # Output: {1, 2, 3, 4, 5}

4.3.8 Summary

  • Sets are unordered collections of unique elements, meaning that each element appears only once.
  • You can create sets using curly braces {} or the set() function.
  • Since sets are unordered, you cannot access elements using indexing or slicing, but you can iterate over them.
  • Set operations like union, intersection, difference, and symmetric difference are useful for handling collections of data efficiently.
  • Frozensets are immutable versions of sets, providing all the same operations, but their elements cannot be modified after creation.
  • Sets are particularly useful for removing duplicates, membership testing, and performing mathematical operations.

Sets are an important tool in Python, especially when working with large collections of data that require fast membership testing, removing duplicates, or performing set-based operations. Understanding sets and how to use them effectively is crucial for writing efficient Python code.