Menu
Coddy logo textTech

What is a Set?

Part of the Logic & Flow section of Coddy's Python journey — lesson 29 of 78.

A set is a collection of unique elements. This means that a set cannot contain duplicate values — if you try to add duplicates, Python will automatically remove them for you rather than raising an error. Sets are useful when you need to store a collection of items and ensure that each item appears only once.

Think of a set as a group of distinct items. For example, if you have a basket of fruits and you want to make sure you only have one of each type, you would use a set. In Python, sets are defined using curly braces {}, similar to dictionaries, but without key-value pairs.

Here's an example of how to create a set:

# Creating a set of numbers
numbers = {1, 2, 3, 4, 5}

# Creating a set of strings
fruits = {"apple", "banana", "cherry"}

# Creating an empty set
empty_set = set()

In the first example, numbers is a set containing the numbers 1 through 5. In the second example, fruits is a set containing the strings "apple", "banana", and "cherry". The third example shows how to create an empty set using the set() constructor. Note that you cannot create an empty set using empty curly braces {} because that would create an empty dictionary instead.

As mentioned, Python handles duplicates automatically. For example, {1, 2, 2, 3} will simply become {1, 2, 3} — the duplicate 2 is silently discarded.

challenge icon

Challenge

Easy

Write a program that:

  1. Creates a set called numbers containing the values 1, 2, 3, 4, 5.
  2. Creates a set called fruits containing the values "apple", "banana", and "cherry".
  3. Prints both sets.

The test cases can seem weird but they are OK, notice that sets are unordered so they can be printed in any order

Cheat sheet

A set is a collection of unique elements that cannot contain duplicate values. Sets are defined using curly braces {}:

# Creating a set of numbers
numbers = {1, 2, 3, 4, 5}

# Creating a set of strings
fruits = {"apple", "banana", "cherry"}

# Creating an empty set
empty_set = set()

Note: Use set() to create an empty set, not {} (which creates an empty dictionary). Sets are unordered collections.

Try it yourself

# TODO: Creating the sets
numbers = 
fruits = 

# Printing the sets - DONT MODIFY
print(sorted(numbers))
print(sorted(fruits))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow