Flat_Eric looking in th mirror

Sets

Sets

You’ve made it to the final major data structure in our "Big Four" toolkit! We’ve handled Lists, Dictionaries, and Tuples. Now, we have Sets.

I know, I know—diving into another data type can feel a bit dry. But as we’ve discussed, you don't need to be a walking encyclopedia of syntax. The goal isn't to memorize every method; it’s to know that a process exists so that when you face a specific problem, you know exactly which tool to grab from your belt. Real programming is about research and mindset, not just rote memory.

What is a set?

A Set is a collection that is unordered, unindexed, and—most importantly contains no duplicate members.

Think of a set like a physical bag of labeled marbles. You can reach in and grab one, but they aren't sitting in a neat line (unordered), and you can’t have two marbles that are exactly the same.

Set Syntax

Sets are written with curly braces {}, just like dictionaries, but they don't have "keys" or "colon pairs." They just have items.

Basic Set Methods

Since you can't use an index to change an item, you use these methods to manage the items in your set:

  1. Print skills.
  2. Remove HTML from skills and print again.
  3. Discard C++ from skills and print again.
  4. Clear skills and print.

Because sets are unordered, we cannot find data using slicing. However, we can use the in keyword to see if a specific value is in the set.

One last caveat: because sets only store unique values, if we have a set nums = {2, 3, 3, 4, 4, 4, 6, 6, 6, 6, 6, 6} and we check the length using len(nums), we get 4, not 12. This is because Python ignores all those duplicate entries.

Scenario: Removing Duplicates

We can use the set() function to return a set with no duplicates from a list that has repeated items:

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Set Creation

Exercise 2: Adding and Removing

Exercise 3: Membership Testing

Exercise 4: The Length Caveat

Exercise 5: Instant Deduplication

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course