Sets in Python

    Kedar Kabra3 min readUpdated

    A set is a collection that holds only unique items, with no duplicates and no fixed order. You write it with curly braces:

    numbers = {1, 2, 3, 3, 2, 1}
    print(numbers)        # {1, 2, 3} — duplicates removed automatically
    

    That automatic de-duplication is the headline feature. Sets are also fast at checking "is this item present?". Let's explore.

    Creating sets

    Use curly braces with comma-separated items, or the set() function. There's one catch: an empty {} makes a dictionary, not a set — so use set() for an empty one:

    fruits = {"apple", "banana", "cherry"}
    
    empty_set = set()        # correct way to make an empty set
    not_a_set = {}           # this is an empty DICTIONARY!
    
    # Turn a list into a set (great for removing duplicates)
    nums = [1, 2, 2, 3, 3, 3]
    unique = set(nums)
    print(unique)            # {1, 2, 3}
    

    Adding and removing

    colours = {"red", "green"}
    
    colours.add("blue")          # add one item
    print(colours)               # {'red', 'green', 'blue'}
    
    colours.discard("green")     # remove if present (no error if missing)
    colours.remove("red")        # remove, but errors if missing
    
    print(colours)               # {'blue'}
    

    Use .discard() when you're not sure the item exists — unlike .remove(), it won't crash on a missing item.

    Sets have no order or index

    Because sets are unordered, you cannot access items by position. my_set[0] raises an error. You can only check membership or loop over them:

    fruits = {"apple", "banana", "cherry"}
    
    # Membership check — this is very fast
    print("apple" in fruits)     # True
    print("mango" in fruits)     # False
    
    # Looping works, but order is not guaranteed
    for fruit in fruits:
        print(fruit)
    

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses

    Set operations: the real superpower

    Sets shine when comparing groups. Python supports the same operations you learned in maths:

    maths = {"Asha", "Ravi", "Meena"}
    science = {"Ravi", "Meena", "Kiran"}
    
    # Union: everyone in either class
    print(maths | science)       # {'Asha', 'Ravi', 'Meena', 'Kiran'}
    
    # Intersection: students in BOTH classes
    print(maths & science)       # {'Ravi', 'Meena'}
    
    # Difference: in maths but NOT in science
    print(maths - science)       # {'Asha'}
    
    # Symmetric difference: in one class but not both
    print(maths ^ science)       # {'Asha', 'Kiran'}
    

    These read almost like English and replace what would otherwise be messy loops.

    A practical example

    # Find common interests between two people
    
    asha_likes = {"coding", "music", "cricket", "reading"}
    ravi_likes = {"cricket", "movies", "coding", "gaming"}
    
    # What do they have in common?
    common = asha_likes & ravi_likes
    print(f"Shared interests: {common}")
    # Shared interests: {'coding', 'cricket'}
    
    # What's unique to Asha?
    only_asha = asha_likes - ravi_likes
    print(f"Only Asha likes: {only_asha}")
    

    Common mistakes

    • Using {} for an empty set: {} creates an empty dictionary. Use set() instead.
    • Expecting order: Sets don't keep insertion order. Don't rely on items printing in any particular sequence; if order matters, use a list.
    • Indexing a set: my_set[0] raises a TypeError. Sets have no positions.
    • .remove() on a missing item: It raises a KeyError. Use .discard() if the item may not be there.
    • Putting unhashable items in a set: A set can't contain lists or other sets (they're mutable). It can hold numbers, strings, and tuples.

    FAQ

    When should I use a set instead of a list? Use a set when you need unique items, fast membership tests, or set maths (union/intersection). Use a list when order matters or duplicates are allowed.

    How do I remove duplicates from a list but keep order? Convert to a set and back loses order. To keep order, use list(dict.fromkeys(my_list)), which preserves first-seen order while dropping duplicates.

    Is there an immutable set? Yes — frozenset() creates a set that can't be changed, useful as a dictionary key or set member.


    Sets round out Python's core collections alongside Lists in Python and Dictionaries in Python. Browse everything on the Python learning hub.

    Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.

    Want to learn this properly?

    Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.

    Browse courses
    Kedar Kabra

    Instructor, Infoplanet

    Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.

    Related guides