Python - Set Exercises

Hello there, future Python wizards! Today, we're going to dive into the magical world of Python sets. Don't worry if you've never coded before – I'll be your friendly guide on this exciting journey. By the end of this tutorial, you'll be conjuring up sets like a pro!

Python - Set Exercises

What is a Set?

Before we jump into our exercises, let's quickly understand what a set is in Python. Imagine you have a bag of marbles, but each marble can only appear once in the bag. That's essentially what a set is in Python – a collection of unique items.

Sets are unordered, which means the items don't have a specific position. They're also mutable, so we can add or remove items. However, the items themselves must be immutable (like numbers or strings, not lists).

Now, let's roll up our sleeves and get coding!

Python Set Exercise 1: Creating and Manipulating Sets

Creating a Set

Let's start by creating a simple set:

fruits = {"apple", "banana", "cherry"}
print(fruits)

When you run this code, you'll see:

{'cherry', 'banana', 'apple'}

Notice how the order might be different from what we input? That's because sets are unordered!

Adding Items to a Set

Now, let's add some more fruits to our set:

fruits.add("dragonfruit")
print(fruits)

fruits.update(["elderberry", "fig"])
print(fruits)

Output:

{'cherry', 'banana', 'apple', 'dragonfruit'}
{'fig', 'cherry', 'banana', 'elderberry', 'apple', 'dragonfruit'}

See how we used add() for a single item and update() for multiple items? It's like adding one marble to your bag versus pouring in a handful!

Removing Items from a Set

Let's remove some fruits:

fruits.remove("banana")
print(fruits)

fruits.discard("grape")  # This won't raise an error even if "grape" isn't in the set
print(fruits)

Output:

{'fig', 'cherry', 'elderberry', 'apple', 'dragonfruit'}
{'fig', 'cherry', 'elderberry', 'apple', 'dragonfruit'}

remove() will raise an error if the item doesn't exist, while discard() won't. It's like carefully picking out a specific marble versus casually looking for one to remove.

Python Set Exercise 2: Set Operations

Now that we've mastered the basics, let's play with multiple sets!

Union of Sets

Imagine you and your friend both have bags of marbles. The union is all the unique marbles you have together.

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
union_set = set1.union(set2)
print(union_set)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

Intersection of Sets

The intersection is the marbles you both have in common.

intersection_set = set1.intersection(set2)
print(intersection_set)

Output:

{4, 5}

Difference of Sets

The difference is the marbles you have that your friend doesn't.

difference_set = set1.difference(set2)
print(difference_set)

Output:

{1, 2, 3}

Python Set Exercise 3: Advanced Set Operations

Ready to level up? Let's tackle some more advanced operations!

Symmetric Difference

This gives us all the marbles that are in either set, but not in both.

symmetric_difference = set1.symmetric_difference(set2)
print(symmetric_difference)

Output:

{1, 2, 3, 6, 7, 8}

Subset and Superset

Let's check if one set is contained within another:

set3 = {1, 2, 3}
print(set3.issubset(set1))  # Is set3 a subset of set1?
print(set1.issuperset(set3))  # Is set1 a superset of set3?

Output:

True
True

It's like checking if all your marbles are also in your friend's bigger collection!

Frozen Sets

Sometimes, we need a set that can't be changed. Enter the frozen set:

frozen_fruits = frozenset(["apple", "banana", "cherry"])
print(frozen_fruits)

# This will raise an error:
# frozen_fruits.add("dragonfruit")

Output:

frozenset({'cherry', 'banana', 'apple'})

Think of a frozen set as a bag of marbles sealed in ice – you can look, but you can't touch!

Summary of Set Methods

Here's a handy table of the set methods we've learned:

Method Description
add() Adds an element to the set
update() Updates the set with elements from another set or iterable
remove() Removes a specified element (raises error if not found)
discard() Removes a specified element (no error if not found)
union() Returns a set containing the union of sets
intersection() Returns a set containing the intersection of sets
difference() Returns a set containing the difference between sets
symmetric_difference() Returns a set with elements in either set, but not both
issubset() Checks if a set is a subset of another set
issuperset() Checks if a set is a superset of another set

And there you have it, folks! You've just leveled up your Python skills with sets. Remember, practice makes perfect, so keep playing with these concepts. Before you know it, you'll be manipulating sets like a true Python sorcerer!

Credits: Image by storyset