Table of Contents

    Sets

    Programming Mastery

    Sets

    Learn how sets store unique values and help programmers remove duplicates, test membership, and perform powerful operations like union, intersection, and difference.

    What is a Set?

    A set is a data structure used to store a collection of unique elements.

    In simple words, a set is a collection where duplicate values are not allowed. If the same value is added more than once, the set keeps only one copy.

    A set is a collection of distinct values where each element appears only once.

    Example:

    numbers = {10, 20, 30, 20, 10}
    
    After removing duplicates:
    numbers = {10, 20, 30}

    Here, duplicate values 10 and 20 appear more than once, but the set stores them only once.

    Easy Real-Life Example

    Set as a Unique Attendance Register

    Imagine a classroom attendance register where each student name should appear only once. Even if a student signs twice by mistake, the final attendance list should contain the name only once.

    attendance = {"Aman", "Riya", "Sohan", "Aman"}
    
    Final unique attendance:
    {"Aman", "Riya", "Sohan"}

    This is exactly what a set does. It automatically helps us maintain unique values.

    Why are Sets Used?

    Sets are used when we need to store values without duplicates or when we need to compare groups of values.

    Sets are Used For

    • Removing duplicate values from a collection.
    • Checking whether an item exists in a group.
    • Finding common elements between two groups.
    • Combining unique values from multiple groups.
    • Finding values present in one group but not another.
    • Managing tags, categories, roles, permissions, and unique IDs.
    • Comparing student enrollments, product lists, or user groups.
    • Solving mathematical set problems in programming.
    Key Idea: Use sets when uniqueness matters.

    Important Terms Related to Sets

    Term Meaning Example
    Set A collection of unique elements. {1, 2, 3}
    Element Each value stored inside a set. 1, 2, 3
    Unique No duplicate values are stored. {1, 1, 2} becomes {1, 2}
    Membership Checking whether an element exists in a set. 2 IN {1, 2, 3}
    Union Combines all unique elements from sets. A ∪ B
    Intersection Finds common elements between sets. A ∩ B
    Difference Finds elements in one set but not another. A - B

    General Syntax of a Set

    The exact syntax differs from language to language, but sets are commonly represented using curly braces or a set constructor.

    setName = {value1, value2, value3}

    Example:

    numbers = {10, 20, 30}
    names = {"Aman", "Riya", "Sohan"}
    vowels = {"a", "e", "i", "o", "u"}
    Language-Neutral Note: Some languages use special classes or constructors to create sets, but the concept remains the same: store unique values.

    Main Characteristics of Sets

    Key Characteristics

    • Sets store only unique elements.
    • Sets are usually unordered.
    • Sets are useful for fast membership checking.
    • Sets can add and remove elements.
    • Sets are used for mathematical operations like union and intersection.
    • Sets are useful when duplicate values should be ignored.

    Duplicate Values in Sets

    The most important rule of a set is that duplicates are not allowed.

    numbers = {1, 2, 2, 3, 3, 3}
    
    Stored set:
    {1, 2, 3}

    Even though 2 and 3 were repeated, the set stores each value only once.

    Sets are Usually Unordered

    In many programming languages, sets do not guarantee a fixed order of elements.

    colors = {"Red", "Green", "Blue"}

    The set may not always display elements in the same order in which they were inserted.

    Important: If order is important, a list may be a better choice. If uniqueness is important, a set is often better.

    Adding Elements to a Set

    We can add new elements to a set. If the element already exists, the set usually remains unchanged.

    /*
    This program adds elements to a set.
    */
    
    ENTRY POINT
        DECLARE numbers AS SET = {10, 20, 30}
    
        ADD 40 TO numbers
        ADD 20 TO numbers
    
        DISPLAY numbers
    END ENTRY POINT

    Expected Output

    {10, 20, 30, 40}

    The value 20 was already present, so it was not added again.

    Removing Elements from a Set

    We can remove an element from a set when it is no longer needed.

    /*
    This program removes an element from a set.
    */
    
    ENTRY POINT
        DECLARE fruits AS SET = {"Apple", "Banana", "Mango"}
    
        REMOVE "Banana" FROM fruits
    
        DISPLAY fruits
    END ENTRY POINT

    Expected Output

    {"Apple", "Mango"}

    Membership Testing

    Membership testing means checking whether a value exists in a set.

    Sets are commonly used for membership testing because they are often optimized for this purpose.

    /*
    This program checks membership in a set.
    */
    
    ENTRY POINT
        DECLARE allowedRoles AS SET = {"Admin", "Editor", "Viewer"}
        DECLARE userRole AS TEXT = "Editor"
    
        IF userRole IN allowedRoles THEN
            DISPLAY "Access allowed"
        ELSE
            DISPLAY "Access denied"
        END IF
    END ENTRY POINT

    Expected Output

    Access allowed

    Common Set Operations

    Sets support several important mathematical operations.

    Operation Meaning Example Result
    Union All unique elements from both sets. {1, 2} ∪ {2, 3} = {1, 2, 3}
    Intersection Only common elements. {1, 2} ∩ {2, 3} = {2}
    Difference Elements in first set but not in second. {1, 2} - {2, 3} = {1}
    Symmetric Difference Elements in either set, but not in both. {1, 2} △ {2, 3} = {1, 3}
    Subset Checks whether all elements of one set exist in another. {1, 2} is subset of {1, 2, 3}
    Superset Checks whether one set contains all elements of another. {1, 2, 3} is superset of {1, 2}

    1. Union of Sets

    Union combines all unique elements from two sets.

    A = {1, 2, 3}
    B = {3, 4, 5}
    
    A UNION B = {1, 2, 3, 4, 5}

    Example: Union

    /*
    This program finds the union of two sets.
    */
    
    ENTRY POINT
        DECLARE setA AS SET = {1, 2, 3}
        DECLARE setB AS SET = {3, 4, 5}
    
        DECLARE result AS SET = setA UNION setB
    
        DISPLAY result
    END ENTRY POINT

    Expected Output

    {1, 2, 3, 4, 5}

    2. Intersection of Sets

    Intersection returns only the elements that are common in both sets.

    A = {1, 2, 3}
    B = {3, 4, 5}
    
    A INTERSECTION B = {3}

    Example: Intersection

    /*
    This program finds common elements between two sets.
    */
    
    ENTRY POINT
        DECLARE pythonStudents AS SET = {"Aman", "Riya", "Sohan"}
        DECLARE databaseStudents AS SET = {"Riya", "Meera", "Sohan"}
    
        DECLARE commonStudents AS SET = pythonStudents INTERSECTION databaseStudents
    
        DISPLAY commonStudents
    END ENTRY POINT

    Expected Output

    {"Riya", "Sohan"}

    3. Difference of Sets

    Difference returns elements that are present in the first set but not in the second set.

    A = {1, 2, 3}
    B = {3, 4, 5}
    
    A DIFFERENCE B = {1, 2}

    Example: Difference

    /*
    This program finds students only in the first course.
    */
    
    ENTRY POINT
        DECLARE courseA AS SET = {"Aman", "Riya", "Sohan"}
        DECLARE courseB AS SET = {"Riya", "Meera"}
    
        DECLARE onlyCourseA AS SET = courseA DIFFERENCE courseB
    
        DISPLAY onlyCourseA
    END ENTRY POINT

    Expected Output

    {"Aman", "Sohan"}

    4. Symmetric Difference

    Symmetric difference returns elements that are present in either set, but not in both.

    A = {1, 2, 3}
    B = {3, 4, 5}
    
    A SYMMETRIC DIFFERENCE B = {1, 2, 4, 5}

    Example: Symmetric Difference

    /*
    This program finds students who are in only one of the two groups.
    */
    
    ENTRY POINT
        DECLARE groupA AS SET = {"Aman", "Riya", "Sohan"}
        DECLARE groupB AS SET = {"Riya", "Meera", "Karan"}
    
        DECLARE onlyOneGroup AS SET = groupA SYMMETRIC_DIFFERENCE groupB
    
        DISPLAY onlyOneGroup
    END ENTRY POINT

    Expected Output

    {"Aman", "Sohan", "Meera", "Karan"}

    Removing Duplicates Using a Set

    One of the most practical uses of sets is removing duplicate values.

    /*
    This program removes duplicate numbers using a set.
    */
    
    ENTRY POINT
        DECLARE numbers AS LIST = [10, 20, 10, 30, 20, 40]
    
        DECLARE uniqueNumbers AS SET = CONVERT numbers TO SET
    
        DISPLAY uniqueNumbers
    END ENTRY POINT

    Expected Output

    {10, 20, 30, 40}

    Set vs List

    Lists and sets both store multiple values, but they are used for different purposes.

    Feature List Set
    Duplicates Allows duplicate values. Does not allow duplicate values.
    Order Usually maintains insertion order. Usually unordered.
    Indexing Elements can usually be accessed by index. Elements usually cannot be accessed by index.
    Best For Ordered collections. Unique collections and membership testing.
    Example [10, 20, 20] {10, 20}

    Real-World Example: Course Enrollment

    Suppose two courses have some students enrolled. We can use sets to find all students, common students, and students enrolled only in one course.

    /*
    This program compares students enrolled in two courses.
    */
    
    ENTRY POINT
        DECLARE programmingCourse AS SET = {"Aman", "Riya", "Sohan", "Meera"}
        DECLARE databaseCourse AS SET = {"Riya", "Sohan", "Karan"}
    
        DECLARE allStudents AS SET = programmingCourse UNION databaseCourse
        DECLARE commonStudents AS SET = programmingCourse INTERSECTION databaseCourse
        DECLARE onlyProgramming AS SET = programmingCourse DIFFERENCE databaseCourse
    
        DISPLAY "All Students: " + allStudents
        DISPLAY "Common Students: " + commonStudents
        DISPLAY "Only Programming Course: " + onlyProgramming
    END ENTRY POINT

    Expected Output

    All Students: {"Aman", "Riya", "Sohan", "Meera", "Karan"}
    Common Students: {"Riya", "Sohan"}
    Only Programming Course: {"Aman", "Meera"}

    Real-World Example: User Permissions

    Sets are useful for checking roles and permissions.

    /*
    This program checks whether a user has required permission.
    */
    
    ENTRY POINT
        DECLARE userPermissions AS SET = {"read", "write", "download"}
        DECLARE requiredPermission AS TEXT = "write"
    
        IF requiredPermission IN userPermissions THEN
            DISPLAY "Permission granted"
        ELSE
            DISPLAY "Permission denied"
        END IF
    END ENTRY POINT

    Expected Output

    Permission granted

    Advantages of Sets

    Benefits

    • Sets automatically remove duplicate values.
    • Sets are useful for checking whether a value exists.
    • Sets make union, intersection, and difference operations easy.
    • Sets are useful for comparing groups of data.
    • Sets help write cleaner logic for unique values.
    • Sets are useful in data cleaning and validation.
    • Sets are helpful in algorithms and problem-solving.

    Limitations of Sets

    Limitations

    • Sets usually do not maintain element order.
    • Sets usually do not support index-based access.
    • Duplicate values cannot be stored.
    • Some languages require set elements to be immutable or hashable.
    • Sets may not be suitable when repeated values are meaningful.
    • Sets are not ideal when element position matters.

    Common Beginner Mistakes

    Mistakes

    • Expecting sets to store duplicate values.
    • Expecting sets to keep elements in insertion order.
    • Trying to access set elements using indexes.
    • Confusing union with intersection.
    • Confusing difference with symmetric difference.
    • Using a set when a list is needed for ordered data.
    • Forgetting that duplicate items are automatically removed.
    • Not checking whether an item exists before removing it in some languages.

    Better Habits

    • Use sets when uniqueness is required.
    • Use lists when order and duplicates matter.
    • Use union to combine unique values.
    • Use intersection to find common values.
    • Use difference to find values only in one set.
    • Use membership testing for quick existence checks.
    • Use meaningful set names such as uniqueNames, allowedRoles, and selectedTags.
    • Practice set operations with real-world groups.

    Best Practices for Sets

    Recommended Practices

    • Use sets to remove duplicates from data.
    • Use sets for membership testing.
    • Use sets to compare two or more groups.
    • Use clear names that describe uniqueness, such as uniqueEmails.
    • Do not use sets if duplicate values are important.
    • Do not depend on element order unless the language provides an ordered set type.
    • Use union, intersection, and difference to simplify comparison logic.
    • Convert lists to sets when you need uniqueness.
    • Convert sets back to lists when ordering or indexing is required.
    • Test set logic with duplicate, empty, and overlapping data.

    Prerequisites Before Learning Sets

    Students should already understand:

    Required Knowledge

    • Variables and constants.
    • Data types.
    • Input and output.
    • Conditions.
    • Loops and iteration.
    • Lists and arrays.
    • Searching basics.
    • Basic mathematical idea of unique values.

    Trace Table Example: Remove Duplicates

    Let us understand how a set removes duplicates.

    values = [10, 20, 10, 30, 20]
    uniqueValues = empty set
    
    FOR each value IN values
        ADD value TO uniqueValues
    END FOR
    Step Current Value Action Set Status
    1 10 Add {10}
    2 20 Add {10, 20}
    3 10 Already exists {10, 20}
    4 30 Add {10, 20, 30}
    5 20 Already exists {10, 20, 30}

    Practice Activity: Set Operations

    Study the following two sets:

    A = {1, 2, 3, 4}
    B = {3, 4, 5, 6}

    Questions

    1. What is A UNION B?
    2. What is A INTERSECTION B?
    3. What is A DIFFERENCE B?
    4. What is B DIFFERENCE A?
    5. What is A SYMMETRIC DIFFERENCE B?

    Sample Answers

    1. A UNION B = {1, 2, 3, 4, 5, 6}
    2. A INTERSECTION B = {3, 4}
    3. A DIFFERENCE B = {1, 2}
    4. B DIFFERENCE A = {5, 6}
    5. A SYMMETRIC DIFFERENCE B = {1, 2, 5, 6}

    Mini Quiz

    1

    What is a set?

    A set is a collection of unique elements where duplicate values are not allowed.

    2

    Can a set contain duplicate values?

    No. A set stores each value only once.

    3

    What is union of sets?

    Union combines all unique elements from two or more sets.

    4

    What is intersection of sets?

    Intersection returns elements that are common in both sets.

    5

    When should we use a set?

    We should use a set when we need unique values, membership testing, or comparison between groups.

    Interview Questions on Sets

    1

    Define set in programming.

    A set is a data structure that stores a collection of distinct elements.

    2

    How is a set different from a list?

    A list can store duplicates and usually maintains order, while a set stores unique values and is usually unordered.

    3

    What are common set operations?

    Common set operations include union, intersection, difference, symmetric difference, subset, and superset.

    4

    Why are sets useful for removing duplicates?

    Sets automatically store only unique values, so duplicate values are ignored or removed.

    5

    What is membership testing in sets?

    Membership testing means checking whether a value exists in a set.

    Quick Summary

    Concept Meaning
    Set A collection of unique elements.
    Duplicate Repeated value; not allowed in a set.
    Membership Checking whether an item exists in a set.
    Union Combines all unique elements.
    Intersection Finds common elements.
    Difference Finds elements in one set but not another.
    Best Use Removing duplicates, checking membership, and comparing groups.

    Final Takeaway

    Sets are powerful data structures used to store unique values. They are useful for removing duplicates, checking membership, and comparing groups through operations such as union, intersection, difference, and symmetric difference. In the Programming Mastery Course, students should understand sets as a practical tool for handling uniqueness, permissions, tags, enrollments, categories, and many real-world comparison problems.