How to Check If a List Contains Only Unique Elements in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a list contains only unique elements in Python. The lab focuses on using Python sets to define and identify unique elements within a list.

The lab guides you through creating a Python script, unique_elements.py, to demonstrate how sets work. You'll create a list with duplicate elements, convert it to a set to remove duplicates, and then print both the original list and the resulting set of unique elements. By comparing the original list with the set, you'll understand how sets can be used to identify and extract unique elements.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/DataStructuresGroup -.-> python/sets("Sets") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/sets -.-> lab-559529{{"How to Check If a List Contains Only Unique Elements in Python"}} python/build_in_functions -.-> lab-559529{{"How to Check If a List Contains Only Unique Elements in Python"}} python/data_collections -.-> lab-559529{{"How to Check If a List Contains Only Unique Elements in Python"}} end

Define Unique Elements

In this step, you will learn how to define unique elements using Python sets. Sets are a fundamental data structure in Python that only store unique, unordered elements. This means that if you try to add a duplicate element to a set, it will simply be ignored. Understanding sets is crucial for tasks like removing duplicates from a list or checking for the presence of an element in a collection.

Let's start by creating a Python script to demonstrate how sets work.

  1. Open your WebIDE. You should see the file explorer on the left and a text editor on the right.

  2. In the file explorer, navigate to your project directory: /home/labex/project.

  3. Create a new file named unique_elements.py by right-clicking in the file explorer and selecting "New File".

  4. Open unique_elements.py in the editor and add the following code:

## Create a list with duplicate elements
my_list = [1, 2, 2, 3, 4, 4, 5]

## Convert the list to a set to remove duplicates
my_set = set(my_list)

## Print the original list and the set
print("Original List:", my_list)
print("Set of Unique Elements:", my_set)

This script first creates a list called my_list that contains duplicate elements. Then, it converts this list into a set called my_set. The set() function automatically removes any duplicate elements, leaving only the unique values. Finally, the script prints both the original list and the set of unique elements.

  1. Save the unique_elements.py file.

  2. Now, run the script using the following command in the terminal:

python unique_elements.py

You should see the following output:

Original List: [1, 2, 2, 3, 4, 4, 5]
Set of Unique Elements: {1, 2, 3, 4, 5}

As you can see, the set my_set only contains the unique elements from the original list my_list. The order of elements in the set may be different from the original list because sets are unordered.

This example demonstrates the basic usage of sets for defining unique elements in Python. In the next steps, you will explore more advanced operations with sets.

Compare len() with len(set())

In this step, you will learn how to use the len() function to determine the number of elements in a list and compare it with the number of unique elements in a set created from the same list. This is a useful technique for identifying the number of duplicate elements in a list.

The len() function returns the number of items in an object. When applied to a list, it returns the total number of elements, including duplicates. When applied to a set, it returns the number of unique elements.

Let's modify the Python script from the previous step to compare the lengths of the original list and the set of unique elements.

  1. Open the unique_elements.py file in your WebIDE, which you created in the previous step. It should be located in /home/labex/project.

  2. Modify the unique_elements.py file to include the following code:

## Create a list with duplicate elements
my_list = [1, 2, 2, 3, 4, 4, 5]

## Convert the list to a set to remove duplicates
my_set = set(my_list)

## Print the length of the original list and the set
print("Length of Original List:", len(my_list))
print("Length of Set of Unique Elements:", len(my_set))

## Calculate the number of duplicate elements
num_duplicates = len(my_list) - len(my_set)
print("Number of Duplicate Elements:", num_duplicates)

In this script, we've added code to calculate and print the lengths of both the original list and the set of unique elements. We then calculate the number of duplicate elements by subtracting the length of the set from the length of the list.

  1. Save the unique_elements.py file.

  2. Run the script using the following command in the terminal:

python unique_elements.py

You should see the following output:

Length of Original List: 7
Length of Set of Unique Elements: 5
Number of Duplicate Elements: 2

This output shows that the original list has 7 elements, while the set of unique elements has 5 elements. The difference between these lengths (7 - 5 = 2) indicates that there are 2 duplicate elements in the original list.

This example demonstrates how to use the len() function in conjunction with sets to identify and quantify duplicate elements in a list.

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.

  1. Open the unique_elements.py file in your WebIDE, which you created in the previous steps. It should be located in /home/labex/project.

  2. 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.

  1. Save the unique_elements.py file.

  2. 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.

Summary

In this lab, you learned how to define unique elements using Python sets. The lab involved creating a Python script named unique_elements.py to demonstrate how sets work. You created a list with duplicate elements and then converted it into a set using the set() function, which automatically removes any duplicate elements, leaving only the unique values.

The script then printed both the original list and the set of unique elements, showcasing how sets can be used to extract unique values from a list. You observed that the order of elements in the set may differ from the original list due to the unordered nature of sets.