PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Sets in Python

Sets in Python

Updated on: December 4, 2026 | 18 Comments

A set in Python is an unordered collection of unique items. Sets automatically remove duplicates, check membership very quickly, and support mathematical operations such as union, intersection, and difference.

Unlike a list, a set doesn’t keep items in a fixed order, so you can’t access items by index. In this tutorial, you’ll learn how to create sets, add and remove items, use every set operation, and choose between a set and other data types.

Also See:

  • Python Set Exercise
  • Python Set Quiz
Python Sets
Python Sets

Characteristics of a set

  1. Unordered: Items have no index or position. The order you see when printing a set is arbitrary, so don’t rely on it.
  2. Unique: A set can’t contain the same value twice. Duplicates are dropped automatically.
  3. Mutable, but with immutable items: You can add and remove items, but each item must be hashable (immutable), such as a number, string, or tuple. Lists, dictionaries, and other sets can’t be set items.

Table of contents

  • Creating a set
    • Create a set from a list (remove duplicates)
    • Sets can’t contain mutable items
    • Empty set
  • Accessing items of a set
    • Check if an item exists
  • Find the length of a set
  • Adding items to a set
  • Removing items from a set
    • remove() vs. discard()
  • Set operations
    • Union
    • Intersection
    • Difference
    • Symmetric difference
    • In-place update methods
  • Subset, superset, and disjoint sets
  • Copying a set
  • Sort a set
  • Built-in functions with sets
  • Frozenset
  • Nested sets
  • Set comprehension
  • When to use a set
  • Summary of set methods

Creating a set

There are two ways to create a set:

  • Curly braces: put comma-separated items inside {}.
  • The set() constructor: pass any iterable, such as a list, tuple, string, or range.
# set of mixed types
sample_set = {'Mark', 'Jessa', 25, 75.25}
print(sample_set)        # e.g. {25, 'Mark', 75.25, 'Jessa'} (order varies)
print(type(sample_set))  # <class 'set'>

# set from a tuple
book_set = set(("Harry Potter", "Angels and Demons", "Atlas Shrugged"))
print(sorted(book_set))  # sorted for a predictable displayCode language: Python (python)

Output:

{25, 'Mark', 75.25, 'Jessa'}
<class 'set'>
['Angels and Demons', 'Atlas Shrugged', 'Harry Potter']

Because a set’s order is arbitrary, this tutorial often wraps a set in sorted() so the printed output matches what you’ll see.

Create a set from a list (remove duplicates)

Passing a list to set() keeps only one copy of each value. It’s the quickest way to remove duplicates:

number_list = [20, 30, 20, 30, 50, 30]
unique_numbers = set(number_list)
print(sorted(unique_numbers))   # [20, 30, 50]

print(sorted(set("banana")))    # ['a', 'b', 'n']

# remove duplicates but keep the original order
emails = ["a@x.com", "b@x.com", "a@x.com"]
print(list(dict.fromkeys(emails)))   # ['a@x.com', 'b@x.com']Code language: Python (python)

Sets can’t contain mutable items

Set items must be hashable. Trying to put a list (or dictionary, or set) inside a set raises a TypeError. Use a tuple instead of a list if you need a group of values as one item.

try:
    sample_set = {'Mark', 'Jessa', [35, 78, 92]}
except TypeError as e:
    print(e)   # unhashable type: 'list'

ok_set = {'Mark', 'Jessa', (35, 78, 92)}   # a tuple worksCode language: Python (python)

Empty set

Empty curly braces {} create an empty dictionary, not a set. Use set() for an empty set:

print(type(set()))   # <class 'set'>
print(type({}))      # <class 'dict'>Code language: Python (python)

Accessing items of a set

Sets have no index, so book_set[0] raises a TypeError. To read the items, loop over the set with a for loop:

book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}
for book in sorted(book_set):
    print(book)Code language: Python (python)

Output:

Angels and Demons
Atlas Shrugged
Harry Potter

Check if an item exists

Use the in and not in operators. Membership tests are where sets shine: they take about the same time no matter how big the set is, while a list has to be scanned item by item.

book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}

print('Harry Potter' in book_set)          # True
print("A Man Called Ove" not in book_set)  # TrueCode language: Python (python)

Find the length of a set

book_set = {"Harry Potter", "Angels and Demons", "Atlas Shrugged"}
print(len(book_set))   # 3Code language: Python (python)

Adding items to a set

  • add(item) adds one item. Adding an item that’s already there does nothing.
  • update(iterable, ...) adds every item from one or more iterables.
books = {'Harry Potter', 'Angels and Demons'}

books.add('Ulysses')
books.add('Ulysses')   # duplicate: ignored
books.update(['Atlas Shrugged', 'Ulysses'], ('Dune',))

print(len(books))
print(sorted(books))Code language: Python (python)

Output:

5
['Angels and Demons', 'Atlas Shrugged', 'Dune', 'Harry Potter', 'Ulysses']

Removing items from a set

MethodWhat it does
remove(item)Removes the item. Raises KeyError if it isn’t there.
discard(item)Removes the item if it’s there. Never raises an error.
pop()Removes and returns an arbitrary item. Raises KeyError if the set is empty.
clear()Removes all items.
colors = {'red', 'orange', 'yellow', 'white', 'black'}

colors.remove('yellow')
colors.discard('white')
colors.discard('purple')   # not there: no error
print(sorted(colors))      # ['black', 'orange', 'red']

item = colors.pop()        # removes some item
print(len(colors))         # 2

colors.clear()
print(colors)              # set()Code language: Python (python)

remove() vs. discard()

Use remove() when the item must be there (a missing item is a bug you want to notice). Use discard() when it may or may not be there:

colors = {'red', 'orange'}
colors.discard('purple')   # silently does nothing

try:
    colors.remove('purple')
except KeyError as e:
    print("KeyError:", e)  # KeyError: 'purple'Code language: Python (python)

Set operations

Python supports the classic mathematical set operations, each with an operator and an equivalent method. The examples use these two sets:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}Code language: Python (python)
OperationOperatorMethodResult for a, b
Union (in either)a | ba.union(b){1, 2, 3, 4, 5, 6}
Intersection (in both)a & ba.intersection(b){3, 4}
Difference (in a, not in b)a - ba.difference(b){1, 2}
Symmetric difference (in exactly one)a ^ ba.symmetric_difference(b){1, 2, 5, 6}

Operator vs. method: operators require both sides to be sets. Methods accept any iterable: a.union([7, 8]) works, but a | [7, 8] raises a TypeError.

Union

Python Set Union
Python Set Union
color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
remaining_colors = {'indigo', 'orange', 'red'}

vibgyor = color_set | remaining_colors      # or color_set.union(remaining_colors)
print(len(vibgyor))                         # 7: 'indigo' appears only once
print(sorted(vibgyor))Code language: Python (python)

Output:

7
['blue', 'green', 'indigo', 'orange', 'red', 'violet', 'yellow']

Intersection

Python Set Intersection
Python Set Intersection
color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
remaining_colors = {'indigo', 'orange', 'red'}

print(color_set & remaining_colors)              # {'indigo'}
print(color_set.intersection(remaining_colors))  # {'indigo'}Code language: Python (python)

Difference

Python Set Difference
Python Set Difference

Difference is not symmetric: a - b and b - a give different results.

color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
remaining_colors = {'indigo', 'orange', 'red'}

print(sorted(color_set - remaining_colors))   # ['blue', 'green', 'violet', 'yellow']
print(sorted(remaining_colors - color_set))   # ['orange', 'red']Code language: Python (python)

Symmetric difference

Python Set Symmetric Difference
Python Set Symmetric Difference

The symmetric difference contains items that are in one set or the other, but not both. It’s the union minus the intersection.

color_set = {'violet', 'indigo', 'blue', 'green', 'yellow'}
remaining_colors = {'indigo', 'orange', 'red'}

print(sorted(color_set ^ remaining_colors))
# ['blue', 'green', 'orange', 'red', 'violet', 'yellow']Code language: Python (python)

In-place update methods

The methods above return a new set and leave the original unchanged. Each one also has an in-place version that modifies the set and returns None:

Returns a new setUpdates in placeAugmented operator
union()update()a |= b
intersection()intersection_update()a &= b
difference()difference_update()a -= b
symmetric_difference()symmetric_difference_update()a ^= b
a = {1, 2, 3, 4}
common = a.intersection({2, 3, 9})
print(common, a)        # {2, 3} {1, 2, 3, 4}: a unchanged

result = a.intersection_update({2, 3, 9})
print(result, a)        # None {2, 3}: a changed

c = {1, 2, 3}
c ^= {3, 4}
print(c)                # {1, 2, 4}Code language: Python (python)

Subset, superset, and disjoint sets

  • a.issubset(b) or a <= b: every item of a is in b. Use a < b for a proper subset (a subset that isn’t equal).
  • a.issuperset(b) or a >= b: a contains every item of b.
  • a.isdisjoint(b): the sets have no items in common.
rainbow = {'violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'}
warm = {'orange', 'red', 'yellow'}

print(warm.issubset(rainbow))     # True
print(warm <= rainbow)            # True
print(rainbow.issuperset(warm))   # True
print(warm < warm)                # False: equal, not a proper subset
print(warm.isdisjoint({'blue'}))  # True: nothing in commonCode language: Python (python)

Copying a set

Use copy() or set() to create an independent copy. Assigning with = doesn’t copy: both names refer to the same set, so a change through one name shows up in the other.

colors = {'violet', 'blue'}

copy1 = colors.copy()
copy2 = set(colors)
alias = colors          # not a copy

colors.add('indigo')

print(len(colors), len(copy1), len(copy2), len(alias))   # 3 2 2 3Code language: Python (python)

Sort a set

A set has no order, so it has no sort() method. sorted() returns a new sorted list of the set’s items. (Converting that list back to a set would lose the order again.)

numbers = {20, 4, 6, 10, 8, 15}
print(sorted(numbers))                 # [4, 6, 8, 10, 15, 20]
print(sorted(numbers, reverse=True))   # [20, 15, 10, 8, 6, 4]Code language: Python (python)

Built-in functions with sets

Many built-in functions work on any iterable, including sets:

nums = {2, 4, 15}
print(max(nums), min(nums), sum(nums))   # 15 2 21

# strings compare by Unicode code point: uppercase comes before lowercase
print(max({'ABC', 'abc'}), min({'ABC', 'abc'}))   # abc ABC

print(all({1, 2, 3}))    # True: every item is truthy
print(all({0, 1}))       # False: 0 is falsy
print(any({0, False}))   # False: no truthy item
print(any({0, 1}))       # True
print(all(set()))        # True: an empty set has no falsy itemCode language: Python (python)

Watch out: True == 1 and False == 0 in Python, so {True, 1, 1.0} is the one-item set {True}.

Frozenset

A frozenset is an immutable set. You can’t add or remove items, but you can use all the non-updating operations (union, intersection, and so on). Because it’s immutable, a frozenset is hashable, so it can be a dictionary key or an item of another set.

f = frozenset(['violet', 'indigo', 'blue'])

try:
    f.add('red')
except AttributeError as e:
    print(e)   # 'frozenset' object has no attribute 'add'

combined = f | {'red'}
print(sorted(combined), type(combined).__name__)
# ['blue', 'indigo', 'red', 'violet'] frozenset

# frozenset as a dictionary key: the order of items doesn't matter
pairs = {frozenset({'a', 'b'}): 'pair'}
print(pairs[frozenset({'b', 'a'})])   # pairCode language: Python (python)

Nested sets

A set can’t contain another regular set, because sets aren’t hashable. To build a set of sets, use frozensets as the inner sets:

try:
    nested = {{1, 2}}
except TypeError as e:
    print(e)   # unhashable type: 'set'

groups = {frozenset({1, 2}), frozenset({3})}
print(len(groups))                  # 2
print(frozenset({2, 1}) in groups)  # TrueCode language: Python (python)

Set comprehension

A set comprehension builds a set in one expression, with optional filtering. It’s like a list comprehension with curly braces, and duplicates are removed automatically:

{expression for item in iterable if condition}Code language: Python (python)
squares = {n * n for n in range(-3, 4)}
print(sorted(squares))   # [0, 1, 4, 9]: (-3)² and 3² give the same value

words = ["Apple", "apple", "APPLE", "Pear"]
print(sorted({w.lower() for w in words}))   # ['apple', 'pear']Code language: Python (python)

When to use a set

  • Remove duplicates from a collection.
  • Fast membership tests, such as checking whether a user ID is in a large collection of banned IDs.
  • Compare collections: find common items, missing items, or items unique to one side.

Use a list instead when order matters or duplicates are meaningful, and a dictionary when each item needs an associated value.

Summary of set methods

MethodDescription
add(x)Add one item
update(*iterables)Add items from iterables
remove(x) / discard(x)Remove an item (with / without KeyError)
pop() / clear()Remove an arbitrary item / all items
union(), intersection(), difference(), symmetric_difference()Return a new set
*_update() versionsModify the set in place
issubset(), issuperset(), isdisjoint()Compare two sets
copy()Return a shallow copy

Practice: Solve the Python set exercise and take the Python set quiz.

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com