Define Numeric Sets
In this step, you will learn how to define sets containing numbers in Python. Sets are unordered collections of unique elements. This means that a set cannot contain duplicate values. We will focus on creating sets of integers and floats.
First, let's create a Python file named numeric_sets.py
in your ~/project
directory using the VS Code editor.
## Create an empty set
empty_set = set()
print("Empty Set:", empty_set)
## Create a set of integers
integer_set = {1, 2, 3, 4, 5}
print("Integer Set:", integer_set)
## Create a set of floats
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
print("Float Set:", float_set)
## Create a mixed set (integers and floats)
mixed_set = {1, 2.0, 3, 4.5, 5}
print("Mixed Set:", mixed_set)
Save the file as numeric_sets.py
in your ~/project
directory. Now, run the script using the following command in the terminal:
python numeric_sets.py
You should see the following output:
Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
Notice that the order of elements in the set may not be the same as the order in which they were defined. This is because sets are unordered collections. Also, sets automatically remove duplicate values.
Now, let's add some more examples to your numeric_sets.py
file to demonstrate the uniqueness of sets:
## Create a set with duplicate values
duplicate_set = {1, 2, 2, 3, 4, 4, 5}
print("Duplicate Set:", duplicate_set)
## Create a set from a list with duplicate values
duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(duplicate_list)
print("Unique Set from List:", unique_set)
Save the changes and run the script again:
python numeric_sets.py
You should see the following output:
Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
Duplicate Set: {1, 2, 3, 4, 5}
Unique Set from List: {1, 2, 3, 4, 5}
As you can see, the duplicate_set
and unique_set
both contain only unique values, even though we tried to create them with duplicate values.