Understand Set Uniqueness
In this step, you will learn about the unique nature of sets in Python. One of the defining characteristics of a set is that it can only contain unique elements. This means that duplicate values are automatically removed when you create a set. Understanding this property is crucial for effectively using sets in your programs.
Let's create a Python script named uniqueness.py
in your ~/project
directory using the VS Code editor.
## Create a list with duplicate elements
numbers = [1, 2, 2, 3, 4, 4, 5]
## Convert the list to a set
unique_numbers = set(numbers)
## Print the set
print(unique_numbers)
## Check the length of the original list and the set
print(f"Original list length: {len(numbers)}")
print(f"Set length: {len(unique_numbers)}")
In this script:
- We define a list called
numbers
containing several integer elements, including duplicates (e.g., 2
and 4
appear twice).
- We convert the
numbers
list to a set using the set()
constructor. This automatically removes any duplicate values, resulting in a set containing only unique elements.
- We print the
unique_numbers
set to see the unique elements.
- We print the length of the original
numbers
list and the unique_numbers
set to demonstrate how the set removes duplicates.
Now, execute the uniqueness.py
script using the following command in your terminal:
python ~/project/uniqueness.py
You should see the following output:
{1, 2, 3, 4, 5}
Original list length: 7
Set length: 5
This output demonstrates that the set unique_numbers
contains only the unique elements from the original numbers
list, and the length of the set is smaller than the length of the list due to the removal of duplicates.
The uniqueness property of sets makes them useful for tasks such as removing duplicate entries from a collection of data, finding the distinct values in a dataset, and performing mathematical set operations like union, intersection, and difference.