Sets in Python

Sets are unordered collections of unique elements. Unlike lists or tuples, sets do not allow duplicate values. They are useful when you need to ensure that all the elements in a collection are unique.

Creating a Set

You can create a set using curly braces {} or the set() function:

my_set = {1, 2, 3, 4}
my_other_set = set([1, 2, 3, 3, 4])  # Duplicates are removed

Accessing Set Items

Sets are unordered, so you cannot access items by index. However, you can check if an item exists in the set:

print(3 in my_set)  # Outputs: True

Modifying a Set

Sets are mutable, so you can add or remove elements:

my_set.add(5)  # Adds a new element to the set
my_set.remove(1)  # Removes the element 1 from the set

Set Operations

Sets support mathematical operations like union, intersection, and difference, which are useful for working with collections of data:

set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))  # Outputs: {1, 2, 3, 4, 5}
print(set1.intersection(set2))  # Outputs: {3}
print(set1.difference(set2))  # Outputs: {1, 2}

Exercise

Create two sets: one with your favorite fruits and another with fruits available at a store. Use set operations to find which fruits are both in your favorites and available at the store.