Check with set() Conversion
In this step, you will learn how to check if a list contains only unique elements by converting it to a set and comparing the lengths. This is a concise and efficient way to determine if there are any duplicate elements in a list.
The core idea is that if a list contains duplicate elements, converting it to a set will reduce the number of elements because sets only store unique values. If the length of the original list is the same as the length of the set created from it, then the list contains only unique elements.
Let's modify the Python script from the previous steps to check if a list contains only unique elements using set conversion.
-
Open the unique_elements.py
file in your WebIDE, which you created in the previous steps. It should be located in /home/labex/project
.
-
Modify the unique_elements.py
file to include the following code:
## Create a list with or without duplicate elements
my_list = [1, 2, 3, 4, 5] ## Example with unique elements
## my_list = [1, 2, 2, 3, 4, 5] ## Example with duplicate elements
## Convert the list to a set
my_set = set(my_list)
## Check if the list contains only unique elements
if len(my_list) == len(my_set):
print("The list contains only unique elements.")
else:
print("The list contains duplicate elements.")
In this script, we first define a list my_list
. You can choose to use the example with unique elements or the example with duplicate elements by commenting/uncommenting the corresponding lines. Then, we convert the list to a set and compare the lengths of the list and the set. If the lengths are equal, we print a message indicating that the list contains only unique elements; otherwise, we print a message indicating that the list contains duplicate elements.
-
Save the unique_elements.py
file.
-
Run the script using the following command in the terminal:
python unique_elements.py
If you use the example with unique elements (my_list = [1, 2, 3, 4, 5]
), you should see the following output:
The list contains only unique elements.
If you use the example with duplicate elements (my_list = [1, 2, 2, 3, 4, 5]
), you should see the following output:
The list contains duplicate elements.
This example demonstrates how to use set conversion to efficiently check if a list contains only unique elements. This technique is often used in data processing and validation tasks.