Python - Sets

Hello, aspiring Python programmers! Today, we're going to dive into the wonderful world of Python Sets. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfortable, and let's explore sets together!

Python - Sets

Sets in Python

Imagine you have a bag of colorful marbles. Each marble is unique, and you don't care about the order they're in - you just want to know which colors you have. That's essentially what a set is in Python!

A set is an unordered collection of unique elements. It's like a mathematical set: no duplicates allowed, and the order doesn't matter. Sets are incredibly useful when you need to store unique items or perform set operations like union, intersection, and difference.

Creating a Set in Python

Let's start by creating our first set. There are two main ways to create a set in Python:

  1. Using curly braces {}
  2. Using the set() constructor

Here's an example of both methods:

# Method 1: Using curly braces
fruits = {'apple', 'banana', 'cherry'}

# Method 2: Using the set() constructor
colors = set(['red', 'green', 'blue'])

print(fruits)
print(colors)

Output:

{'cherry', 'apple', 'banana'}
{'blue', 'red', 'green'}

Notice how the order of elements in the output might be different from how we defined them. That's because sets are unordered!

Duplicate Elements in Set

Remember when I said sets only contain unique elements? Let's see what happens when we try to add duplicates:

numbers = {1, 2, 3, 2, 4, 3, 5}
print(numbers)

Output:

{1, 2, 3, 4, 5}

As you can see, Python automatically removes the duplicates for us. Isn't that neat?

Adding Elements in a Set

To add a single element to a set, we use the add() method. If we want to add multiple elements at once, we use the update() method.

# Adding a single element
fruits.add('orange')
print(fruits)

# Adding multiple elements
fruits.update(['grape', 'mango'])
print(fruits)

Output:

{'cherry', 'apple', 'banana', 'orange'}
{'cherry', 'mango', 'apple', 'banana', 'orange', 'grape'}

Removing Elements from a Set

There are several ways to remove elements from a set. Let's explore them:

# Using remove() - raises an error if the element doesn't exist
fruits.remove('banana')

# Using discard() - doesn't raise an error if the element doesn't exist
fruits.discard('kiwi')

# Using pop() - removes and returns an arbitrary element
popped = fruits.pop()
print(f"Popped element: {popped}")

# Using clear() - removes all elements
fruits.clear()

print(fruits)

Output:

Popped element: cherry
set()

Membership Testing in a Set

One of the great things about sets is that they allow for very fast membership testing. We can use the in keyword to check if an element exists in a set:

numbers = {1, 2, 3, 4, 5}
print(3 in numbers)  # True
print(6 in numbers)  # False

This operation is much faster with sets than with lists, especially for large collections!

Set Operations

Sets in Python support various mathematical set operations. Let's look at some of them:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union
print(set1 | set2)  # or set1.union(set2)

# Intersection
print(set1 & set2)  # or set1.intersection(set2)

# Difference
print(set1 - set2)  # or set1.difference(set2)

# Symmetric Difference
print(set1 ^ set2)  # or set1.symmetric_difference(set2)

Output:

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

Python Set Comprehensions

Just like list comprehensions, Python also supports set comprehensions. They provide a concise way to create sets based on existing iterable objects.

# Creating a set of squares of numbers from 0 to 9
squares = {x**2 for x in range(10)}
print(squares)

Output:

{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Filtering Elements Using Set Comprehensions

We can also use set comprehensions to filter elements:

# Creating a set of even squares from 0 to 9
even_squares = {x**2 for x in range(10) if x % 2 == 0}
print(even_squares)

Output:

{0, 4, 16, 36, 64}

Nested Set Comprehensions

While less common, nested set comprehensions are also possible:

# Creating a set of tuples (x, y) where x and y are digits
digit_pairs = {(x, y) for x in range(3) for y in range(3)}
print(digit_pairs)

Output:

{(0, 1), (1, 2), (0, 0), (2, 0), (1, 1), (2, 2), (0, 2), (2, 1), (1, 0)}

Frozen Sets

Last but not least, let's talk about frozen sets. A frozen set is an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.

normal_set = {1, 2, 3}
frozen_set = frozenset([1, 2, 3])

normal_set.add(4)  # This works
# frozen_set.add(4)  # This would raise an AttributeError

Frozen sets are particularly useful when you need an immutable set, like using it as a dictionary key.

And there you have it, folks! We've covered the ins and outs of Python sets. Remember, practice makes perfect, so don't hesitate to experiment with these concepts. Happy coding!

Here's a table summarizing the main set methods we've discussed:

Method Description
add() Adds an element to the set
update() Adds multiple elements to the set
remove() Removes a specific element from the set (raises error if not found)
discard() Removes a specific element from the set (no error if not found)
pop() Removes and returns an arbitrary element from the set
clear() Removes all elements from the set
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 of sets
symmetric_difference() Returns a set with elements in either set, but not both

Credits: Image by storyset