Table of Contents

    Mastering Python Sets: Functions, Operations, and Examples

    What is Set in python?

    A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.


    Python’s built-in set type has the following characteristics:

    • Sets are unordered.
    • Set elements are unique. Duplicate elements are not allowed.
    • A set itself may be modified, but the elements contained in the set must be of an immutable type.

    Duplicates Not Allowed

    Sets cannot have two items with the same value.

    vegetableSet  = {"Tomato", "Potato", "Carrot", "Tomato"}
    
    print(vegetableSet)

    Output:

    {'Potato', 'Tomato', 'Carrot'}

    Get the Length of a Set

    To determine how many items a set has, use the len()

    vegetableSet  = {"Tomato", "Potato", "Carrot", "Ginger"}
    
    print(len(vegetableSet))

    Output:

    4

    Practice Quiz 17 MCQs Smart Learning

    Master This Topic with Smart Practice

    Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.

    Topic-wise MCQs
    Instant Results
    Improve Accuracy
    Exam Ready Practice
    Login & Start Quiz Create Free Account
    Save progress • Track results • Learn faster