Skip to content

Python Sets - Basic Operations

CS 5001/5002 - Strings, Sequences & Sets

Code

#!/usr/bin/env python3
"""
Filename: python_sets_basic_operations.py
Description: Python Sets - Basic Operations
CS 5001/5002 - Strings, Sequences & Sets

This script demonstrates basic set operations in Python including creation,
membership testing, and cardinality.
"""

def main():
    # Creating sets in Python
    days_of_week = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
    print(f"Days of week: {days_of_week}")
    print(f"Cardinality: {len(days_of_week)}")

    # Element membership testing
    print(f"'Mon' in days_of_week: {'Mon' in days_of_week}")      # True
    print(f"'January' in days_of_week: {'January' in days_of_week}")  # False

    # Sets automatically remove duplicates
    duplicate_set = {1, 2, 1, 2, 3}
    print(f"Set with duplicates {1, 2, 1, 2, 3} becomes: {duplicate_set}")

    # Cardinality example from the transcript
    S1 = {1, 2, 1, 2}  # Appears to have 4 elements
    S2 = {1, 2}         # Clearly has 2 elements
    print(f"S1 = {S1}, |S1| = {len(S1)}")  # Actually has 2 elements!
    print(f"S2 = {S2}, |S2| = {len(S2)}")  # Has 2 elements
    print(f"S1 == S2: {S1 == S2}")         # They are the same set!

if __name__ == "__main__":
    main()

How to Use

  1. Copy the code above
  2. Save it as a .py file (e.g., python_sets_basic_operations.py)
  3. Run it with: python python_sets_basic_operations.py

Part of CS 5001/5002 - Strings, Sequences & Sets materials