Introduction

I'm delighted to welcome you to our Python Sets lesson! Remember, sets are like lists or tuples, except they can only hold unique elements. They're especially useful when you need to guarantee that elements in a collection appear only once.

In this lesson, you'll consolidate your knowledge of creating and operating on sets. You will learn about the special frozen sets and discover how sets enhance performance. Ready, Set, Go!

Creating and Manipulating Sets

Let's begin by creating a set in Python. It can be done either by the set() function or with {} syntax.

# Creating a set and printing it
my_set = {1, 2, 3, 4, 5, 5, 5}  # Duplicates will be omitted
my_set_2 = set([1, 2, 3, 4, 5, 5, 5]) # The same set
print(my_set)  # Output: {1, 2, 3, 4, 5}
print(my_set_2) # Output: {1, 2, 3, 4, 5}

Python provides methods to manipulate sets, such as add(), in, remove(), and discard().

# Adding an element
my_set.add(6)  # my_set is now {1, 2, 3, 4, 5, 6}

print(1 in my_set) # Output: True, as `my_set` includes an element 1

# Removing an element
my_set.remove(1)  # my_set becomes {2, 3, 4, 5, 6}

print(1 in my_set) # Output: False, as `my_set` doesn't include 1 anymore

# Discarding an element
my_set.discard(7)  # No changes - 7 doesn't exist in my_set

Both remove() and discard() methods are used for removing elements from a set, but they behave slightly differently:

  • remove(): Removes a specified element from the set. If the element is not found, it raises a KeyError.
  • discard(): Also removes a specified element from the set. However, if the element is not found, it does nothing, and no error is raised.
Set Operations

Python provides built-in operations such as union, intersection, and difference for sets.

set_1 = {1, 2, 3, 4}  # First set
set_2 = {3, 4, 5, 6}  # Second set

# Set union
print(set_1.union(set_2))
# Output: {1, 2, 3, 4, 5, 6}

# Set intersection
print(set_1.intersection(set_2))
# Output: {3, 4}

# Set difference
print(set_1.difference(set_2))
# Output: {1, 2}
  • union(): Combines elements from both sets, excluding any duplicates. In this case, the result is a set containing {1, 2, 3, 4, 5, 6}.
  • intersection(): Returns a set with only the elements that are common to both sets. For these sets, the intersection is {3, 4}.
  • difference(): Returns a set containing elements that are in the first set but not in the second set. Here, the result is {1, 2} for set_1.difference(set_2).
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal