• Discover
  • Collections
  • Board
  • Create
  • Profile
  • Settings
Paths

Lesson 5.4: Sets: Unique Elements and Set Operations

Lesson 5.4: Sets: Unique Elements and Set Operations

4 min read

Sets are an unordered collection of unique elements. This means that a set cannot contain duplicate values. Sets are mutable, allowing you to add and remove elements, but the elements themselves must be immutable (like numbers, strings, or tuples). Sets are defined by enclosing elements in curly braces {} or by using the set() constructor.

Creating Sets

python
# An empty set (IMPORTANT: {} creates an empty dictionary, use set() for empty set) empty_set = set() # A set of numbers (duplicates are automatically removed) numbers_set = {1, 2, 3, 2, 1, 4} print(numbers_set) # Output: {1, 2, 3, 4} (order is not guaranteed) # A set of strings fruits_set = {"apple", "banana", "cherry"} print(fruits_set) # Creating a set from a list list_to_set = set(["a", "b", "c", "a"]) print(list_to_set) # Output: {'a', 'b', 'c'} # Sets cannot contain mutable items like lists or dictionaries # invalid_set = {1, [2, 3]} # This would raise a TypeError

Adding and Removing Elements

**1.

Adding elements:

**

  • set.add(item): Adds a single element to the set.
  • set.update(iterable): Adds multiple elements from an iterable (e.g., list, tuple, string) to the set.
python
my_set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} my_set.add(1) # Adding an existing element does nothing print(my_set) # Output: {1, 2, 3, 4} my_set.update([5, 6, 7]) print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7} my_set.update({7, 8, 9}) # Can update with another set print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}

**2.

Removing elements:

**

  • set.remove(item): Removes the specified item. Raises a KeyError if the item is not found.
  • set.discard(item): Removes the specified item if it is present. Does not raise an error if the item is not found.
  • set.pop(): Removes and returns an arbitrary element from the set (since sets are unordered, you don't know which item will be removed).
  • set.clear(): Removes all elements from the set.
python
my_set = {10, 20, 30, 40} my_set.remove(20) print(my_set) # Output: {10, 30, 40} my_set.discard(10) # 10 is present print(my_set) # Output: {30, 40} my_set.discard(99) # 99 is not present, no error print(my_set) # Output: {30, 40} popped_item = my_set.pop() # Removes an arbitrary item (e.g., 30 or 40) print(f"Popped: {popped_item}, Remaining: {my_set}") my_set.clear() print(my_set) # Output: set()

Set Operations

Sets are powerful for performing mathematical set operations:

  • Union (| or set.union()): Returns a new set containing all unique elements from both sets.
  • Intersection (& or set.intersection()): Returns a new set containing elements common to both sets.
  • Difference (- or set.difference()): Returns a new set with elements in the first set but not in the second.
  • Symmetric Difference (^ or set.symmetric_difference()): Returns a new set with elements in either set, but not in both.
python
set_a = {1, 2, 3, 4} set_b = {3, 4, 5, 6} print(f"Union (A | B): {set_a | set_b}") # Output: {1, 2, 3, 4, 5, 6} print(f"Intersection (A & B): {set_a & set_b}") # Output: {3, 4} print(f"Difference (A - B): {set_a - set_b}") # Output: {1, 2} print(f"Symmetric Difference (A ^ B): {set_a ^ set_b}") # Output: {1, 2, 5, 6}

Other Useful Set Methods

  • len(set): Returns the number of items.
  • item in set: Checks for membership (returns True or False). This is very efficient for sets.
  • set.issubset(other_set): Checks if all elements of the set are in other_set.
  • set.issuperset(other_set): Checks if all elements of other_set are in the set.
python
large_set = {1, 2, 3, 4, 5} small_set = {2, 3} print(f"Length of large_set: {len(large_set)}") # Output: 5 print(f"3 in large_set: {3 in large_set}") # Output: True print(f"small_set is a subset of large_set: {small_set.issubset(large_set)}") # Output: True print(f"large_set is a superset of small_set: {large_set.issuperset(small_set)}") # Output: True

Sets are ideal for tasks where you need to store unique items and perform efficient membership tests, or when you need to perform mathematical set operations like finding common elements or differences between collections.

Key Takeaways:

  • Sets are unordered collections of unique, immutable elements, defined with {} or set().
  • Duplicates are automatically removed upon creation or addition.
  • Add elements with add() or update(); remove with remove(), discard(), pop(), or clear().
  • Perform set operations like union (|), intersection (&), difference (-), and symmetric difference (^).
  • Useful for membership testing (in) and checking relationships between collections (issubset, issuperset).
End of lesson
👏Well done!
Previous Lesson
Lesson 5.3: Dictionaries: Key-Value Pairs
Next Lesson
Quiz: Module 5: Basic Data Structures

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 5.1: Lists: Creation, Accessing, Modifying

Lesson 5.2: Tuples: Immutability and Use Cases

Lesson 5.3: Dictionaries: Key-Value Pairs

Lesson 5.4: Sets: Unique Elements and Set Operations

Quiz

Course Content

0% Complete0/22 Lessons

Lesson 1.1: What is Python? History, Features, and Applications

Lesson 1.2: Setting Up Your Python Environment

Lesson 1.3: Your First Python Program: "Hello, World!" and Basic Syntax

Quiz

Lesson 5.1: Lists: Creation, Accessing, Modifying

Lesson 5.2: Tuples: Immutability and Use Cases

Lesson 5.3: Dictionaries: Key-Value Pairs

Lesson 5.4: Sets: Unique Elements and Set Operations

Quiz