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 Examples
  3. Set Operations

Sets · Python example

Set Operations

Compare two skill sets with union, intersection, and difference.

Open the compilerAll examples
beginnersetsunionintersection

Sets store unique values and support mathematical operations. They are ideal for comparing groups of items.

example.py
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "JavaScript", "SQL"}

print("Union:", ", ".join(sorted(frontend | backend)))
print("Intersection:", ", ".join(sorted(frontend & backend)))
print("Frontend only:", ", ".join(sorted(frontend - backend)))

How the code works

  • JavaScript appears in both sets, so it is in the intersection.
  • The union contains every distinct skill.
  • The difference contains HTML and CSS.

Key ideas

  • | computes the union of two sets.
  • & computes the intersection.
  • - computes the items in the first set but not the second.
  • sorted() gives deterministic output.

Try changing it

  • Find skills that are unique to either set with symmetric difference (^).
  • Check whether one set is a subset of another.
  • Remove duplicates from a list by converting it to a set.

Related examples

intermediate

Remove Duplicates while Preserving Order

Use dictionary keys to deduplicate a list without losing the original order.

intermediate

Word Frequency Counter

Count repeated words with a dictionary and print the results in alphabetical order.

Previous exampleWord Frequency CounterNext exampleA Function with a Default Argument

Expected output

Union: CSS, HTML, JavaScript, Python, SQL
Intersection: JavaScript
Frontend only: CSS, HTML

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects