Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Sets: Unique Values and Set Operations

Data structures · Tutorial 18

Python Sets: Unique Values and Set Operations

Remove duplicates with sets, test membership quickly, and use union, intersection, difference, and symmetric difference.

Open the compilerPractice exercises
beginner8 min readUpdated November 19, 20264 learning goals
On this page
  1. Removing duplicates
  2. Membership
  3. Modifying a set
  4. Set operations
  5. Subsets and supersets
  6. Sets of tuples
  7. When to use a set
  8. Practice

What you will learn

  • Create sets and remove duplicates
  • Add and discard items
  • Combine sets with mathematical operations
  • Know when a set is the right tool
Before this lesson: Python Lists: Creation, Indexing, and Iteration, Python Dictionaries: Keys, Values, and Practical Patterns

A set is an unordered collection of unique, hashable values. Duplicates are discarded automatically.

Python
colours = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3, 3, 3])
empty = set()

{} creates an empty dictionary, not an empty set. Use set() for an empty set.

Removing duplicates#

Python
values = [1, 2, 2, 3, 1, 4]
unique = set(values)

print(unique)
print(len(unique))

Sets do not preserve order. If order matters, remove duplicates with dict.fromkeys(values) instead.

Membership#

Set membership is average-case constant time, which makes sets a good choice for repeated lookups:

Python
valid_roles = {"admin", "editor", "viewer"}

print("editor" in valid_roles)  # True
print("owner" in valid_roles)   # False

For one check, a tuple or list is fine. For many checks against the same collection, a set avoids scanning every item each time.

Modifying a set#

Python
tags = {"python", "tutorial"}

tags.add("beginner")
tags.discard("tutorial")

print(tags)

add() inserts one value. discard() removes a value if present and does nothing otherwise. remove() raises KeyError when the value is missing. clear() empties the set.

Set operations#

Python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # union: {1, 2, 3, 4, 5, 6}
print(a & b)   # intersection: {3, 4}
print(a - b)   # difference: {1, 2}
print(b - a)   # {5, 6}
print(a ^ b)   # symmetric difference: {1, 2, 5, 6}

The printed order can vary because sets are unordered. In this environment small integer sets often print in ascending order, but do not depend on it.

Named methods are equivalent and can update in place:

Python
a = {1, 2, 3}
b = {3, 4}

a.update(b)          # union in place
a.intersection_update({2, 3, 4})
a.difference_update({3})

print(a)

Subsets and supersets#

Python
required = {"name", "email"}
provided = {"name", "email", "phone"}

print(required <= provided)   # True: subset
print(provided >= required)   # True: superset
print(required.isdisjoint({"phone", "address"}))  # True

These checks are useful for permission systems and validation.

Sets of tuples#

A set can contain any hashable value, including tuples:

Python
visited = {(0, 0), (1, 2), (0, 0)}
print(visited)  # {(0, 0), (1, 2)}

This is a compact way to track unique coordinates or pairs.

Sets are unordered

Do not index a set, slice it, or assume a particular iteration order. If you need ordered output, convert to a sorted list: sorted(values). Sorting fails for mixed types that cannot be compared.

When to use a set#

  • Removing duplicates when order is irrelevant.
  • Fast membership checks.
  • Comparing collections, such as finding shared or missing items.
  • Tracking seen values during a scan.

Use a list when order and duplicates matter. Use a dictionary when each value needs associated data.

Practice#

Given two lists of names, print the names that appear in both lists, the names that appear in only one, and the total number of unique names. Use set operations rather than nested loops.

Previous tutorialPython Dictionaries: Keys, Values, and Practical PatternsNext tutorialPython Functions: Define, Call, and Return Values

Related tutorials

beginner

Python Functions: Define, Call, and Return Values

Write reusable code with def, pass arguments, return results, and use docstrings to document behaviour.

9 min read
intermediate

Python Error Handling with try, except, else, and finally

Read tracebacks, catch specific exceptions, raise your own errors, and clean up resources reliably.

9 min read

On this page

  1. Removing duplicates
  2. Membership
  3. Modifying a set
  4. Set operations
  5. Subsets and supersets
  6. Sets of tuples
  7. When to use a set
  8. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.