Learn About String Sets
In this step, you will learn about string sets in Python. A set is an unordered collection of unique elements. This means that a set cannot contain duplicate values. Sets are useful for performing mathematical set operations like union, intersection, and difference. In this lab, we will focus on sets containing strings.
First, let's create a simple set of strings. Open the VS Code editor in the LabEx environment. Create a new file named string_sets.py
in the ~/project
directory.
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry"}
print(string_set)
Save the file. Now, run the script using the python
command in the terminal:
python ~/project/string_sets.py
You should see the following output (the order of elements may vary because sets are unordered):
{'cherry', 'banana', 'apple'}
Now, let's add a duplicate element to the set and see what happens:
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry", "apple"}
print(string_set)
Save the file and run it again:
python ~/project/string_sets.py
The output will be:
{'cherry', 'banana', 'apple'}
Notice that the duplicate "apple" was automatically removed. Sets only store unique elements.
Next, let's explore some common set operations. We'll create two sets and perform union and intersection operations.
## ~/project/string_sets.py
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
## Union of two sets
union_set = set1.union(set2)
print("Union:", union_set)
## Intersection of two sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
Save the file and run it:
python ~/project/string_sets.py
The output will be:
Union: {'cherry', 'banana', 'date', 'apple', 'fig'}
Intersection: {'banana'}
The union of the two sets contains all unique elements from both sets. The intersection contains only the elements that are common to both sets.