Skip to content

Set Builder Notation in Python - List Comprehensions

CS 5001/5002 - Strings, Sequences & Sets

Code

#!/usr/bin/env python3
"""
Filename: set_builder_notation.py
Description: Set Builder Notation in Python - List Comprehensions
CS 5001/5002 - Strings, Sequences & Sets

This script demonstrates how to use Python set comprehensions to implement
mathematical set builder notation.
"""

def main():
    # S1 = {x in N | x <= 3}
    S1 = {x for x in range(10) if x <= 3}
    print(f"S1 = {{x in N | x <= 3}} = {S1}")

    # Don't forget 0 is in natural numbers!
    print(f"Note: 0 is included in natural numbers")

    # S2 = {x in N | x >= 3 and x < 5}
    S2 = {x for x in range(10) if x >= 3 and x < 5}
    print(f"S2 = {{x in N | x >= 3 and x < 5}} = {S2}")

    # S3 = {x**2 | x in {1, 2, 3}}
    S3 = {x**2 for x in {1, 2, 3}}
    print(f"S3 = {{x**2 | x in {{1, 2, 3}}}} = {S3}")

    # More complex example: even squares less than 50
    even_squares = {x**2 for x in range(1, 10) if (x**2) % 2 == 0 and x**2 < 50}
    print(f"Even squares < 50: {even_squares}")

    # String example: vowels in a word
    word = "northeastern"
    vowels_in_word = {char for char in word if char in 'aeiou'}
    print(f"Vowels in '{word}': {vowels_in_word}")

if __name__ == "__main__":
    main()

How to Use

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

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