Python Set Operations

Cartoon-style image of two cauldrons labeled Set A and Set B, with magical potion ingredients and sparkles, titled “Set Operations.”

When working with sets in Python, the real magic happens when you start comparing them. Just like overlapping guest lists, playlists, or even shopping baskets, you’ll often want to know what’s shared, what’s unique, or what happens when you combine them. Python makes this easy with four handy operations: union, intersection, difference, and symmetric difference. Each one gives you a different way to compare sets, and together they unlock loads of practical problem-solving power.

Union

The union of two sets combines everything from both, removing duplicates automatically. It’s like merging two guest lists into one.

Example:

Try it yourself:

  • Make two sets of fruits.
  • Union them together.
  • See how duplicates are handled.

Intersection

The intersection finds only the items both sets share. Think of it as asking, “who’s on both the football and chess team?”

Example:

Try it yourself:

  • Create two sets of colours.
  • Find the intersection.
  • Change one set and see how results change.

Difference

The difference shows what’s in one set but not the other. It’s like finding who came to one party but skipped the other.

Example:

Try it yourself:

  • Create two sets of animals.
  • Use .difference() to see which are only in the first.
  • Reverse the difference and compare.

Symmetric Difference

The symmetric difference shows what’s unique to each set — everything except the overlap. It’s like finding the non-shared songs in two playlists.

Example:

Try it yourself:

  • Make two sets of numbers.
  • Use .symmetric_difference().
  • Add another common number to both sets and observe the change.

Main Topic

Introduction to Python Sets

Cartoon elephant holding a football sticker book with unique players, pale lemon background, text reads “Python Sets” beside it.

A guide to Python sets, explaining uniqueness, usefulness, and everyday examples like sticker albums, shopping baskets, and mailing lists.

Other Tutorials in this Topic

Cartoon elephant bouncer blocks a duplicate mouse from entering an animal party, while another mouse is already inside. Text: “Python Sets”.

The basics of Python Sets

A friendly Python sets tutorial explaining uniqueness, adding, removing, and handling duplicates with simple examples, clear explanations,…