The basics of Python Sets

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

Sets are one of Python’s built-in data types. They’re designed to hold a collection of items, but unlike lists, they don’t allow duplicates. This makes them ideal whenever you need a group of unique things. Think of a guest list for a party — no one wants the same person invited twice by accident!

Example:

Here, guests is a set containing three unique names.

Try it yourself:

  • Make a set of three of your favourite foods.
  • Print it out and see the order — does it stay the same each time?

Adding Things to a Set

You can add new items to a set with the .add() method.

Example:

This will add “Daisy” to the set. Notice that sets don’t guarantee order, so the new item might not appear at the end.

Try it yourself:

  • Start with a set of two animals.
  • Add a third animal to the set.
  • Print the set to see where it ends up.

Removing Things from a Set

Sets also let you remove items. The .remove() method will delete an item if it exists, but it will give an error if the item isn’t there. The .discard() method, however, removes an item if it’s there and does nothing if it isn’t.

Example:

Try it yourself:

  • Create a set of three colours.
  • Remove one of them using .remove().
  • Try discarding something that isn’t in the set — what happens?

What Happens with Duplicates?

Here’s where sets shine. If you add the same item more than once, the set simply ignores the duplicate.

Example:

The set will still only contain {"Alice", "Bob"}. No duplicates allowed.

Try it yourself:

  • Make a set with one number in it.
  • Try adding the same number several times.
  • Print the set to see the result.

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-style image of two cauldrons labeled Set A and Set B, with magical potion ingredients and sparkles, titled “Set Operations.”

Python Set Operations

A friendly tutorial on Python set operations, explaining union, intersection, difference, and symmetric difference with clear examples,…