How to Check If a Set Is Sorted When Converted to a List in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a set, when converted to a list in Python, results in a sorted list. The lab explores set conversion from lists to remove duplicates and demonstrates how to convert a set back into a list using the list() function.

You'll then learn how to check if the resulting list is sorted by comparing it to a sorted version of itself. This involves creating Python scripts to convert lists to sets, print the resulting sets, convert the sets back to lists, and finally, implement a method to verify if the list is sorted.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/DataStructuresGroup -.-> python/lists("Lists") 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/lists -.-> lab-559565{{"How to Check If a Set Is Sorted When Converted to a List in Python"}} python/sets -.-> lab-559565{{"How to Check If a Set Is Sorted When Converted to a List in Python"}} python/build_in_functions -.-> lab-559565{{"How to Check If a Set Is Sorted When Converted to a List in Python"}} python/data_collections -.-> lab-559565{{"How to Check If a Set Is Sorted When Converted to a List in Python"}} end

Explore Set Conversion

In this step, you will learn how to convert a list into a set in Python. Sets are unordered collections of unique elements. This means that a set cannot contain duplicate values. Converting a list to a set is a useful way to remove duplicate elements from the list.

First, let's create a Python file named convert_to_set.py in your ~/project directory using the VS Code editor.

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

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

## Print the set
print(my_set)

Now, let's run the Python script. Open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the script using the python command:

python convert_to_set.py

You should see the following output:

{1, 2, 3, 4, 5}

As you can see, the duplicate elements have been removed, and the set contains only unique values.

Let's try another example with strings:

## Create a list of strings with duplicates
string_list = ["apple", "banana", "apple", "orange", "banana"]

## Convert the list to a set
string_set = set(string_list)

## Print the set
print(string_set)

Save the changes to convert_to_set.py and run the script again:

python convert_to_set.py

The output will be:

{'orange', 'banana', 'apple'}

Notice that the order of elements in the set may be different from the original list, as sets are unordered.

Convert to List and Check Sorting

In this step, you will learn how to convert a set back into a list and then check if the list is sorted. This involves using the list() function to convert the set and then comparing the sorted list with the original list.

Let's continue using the convert_to_set.py file in your ~/project directory. We'll add code to convert the set back to a list and then sort it.

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

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

## Convert the set back to a list
my_list_from_set = list(my_set)

## Print the list obtained from the set
print("List from set:", my_list_from_set)

## Sort the list
my_list_from_set.sort()

## Print the sorted list
print("Sorted list:", my_list_from_set)

Now, let's run the Python script. Open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the script using the python command:

python convert_to_set.py

You should see output similar to the following:

List from set: [1, 2, 3, 4, 5, 6, 9]
Sorted list: [1, 2, 3, 4, 5, 6, 9]

The first line shows the list created from the set, which contains unique elements but may not be in the original order. The second line shows the sorted list.

Now, let's add a check to see if the original list (with duplicates removed and converted to a list) is sorted.

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

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

## Convert the set back to a list
my_list_from_set = list(my_set)

## Sort the list
sorted_list = sorted(my_list_from_set)

## Check if the list is sorted
if my_list_from_set == sorted_list:
    print("The list is already sorted.")
else:
    print("The list is not sorted.")

## Print the sorted list
print("Sorted list:", sorted_list)

Run the script again:

python convert_to_set.py

You should see output similar to the following:

The list is not sorted.
Sorted list: [1, 2, 3, 4, 5, 6, 9]

This indicates that the list obtained from the set was not initially sorted, and the sorted() function was used to create a sorted version.

Use sorted() for Comparison

In this step, you will learn how to use the sorted() function for comparison without modifying the original list. The sorted() function returns a new sorted list from the iterable, while the .sort() method sorts the list in-place. This is useful when you want to keep the original list intact.

Let's continue using the convert_to_set.py file in your ~/project directory. We'll modify the code to use sorted() and compare it with the original list.

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

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

## Convert the set back to a list
my_list_from_set = list(my_set)

## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)

## Print the original list from set
print("Original list from set:", my_list_from_set)

## Print the sorted list
print("Sorted list:", sorted_list)

## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
    print("The original list is sorted.")
else:
    print("The original list is not sorted.")

Now, let's run the Python script. Open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the script using the python command:

python convert_to_set.py

You should see output similar to the following:

Original list from set: [1, 2, 3, 4, 5, 6, 9]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is sorted.

In this case, the original list obtained from the set happened to be already sorted. Let's modify the original list to ensure it's not sorted initially.

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

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

## Convert the set back to a list
my_list_from_set = list(my_set)

## Shuffle the list to make sure it's not sorted
import random
random.shuffle(my_list_from_set)

## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)

## Print the original list from set
print("Original list from set:", my_list_from_set)

## Print the sorted list
print("Sorted list:", sorted_list)

## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
    print("The original list is sorted.")
else:
    print("The original list is not sorted.")

Run the script again:

python convert_to_set.py

You should see output similar to the following:

Original list from set: [9, 2, 4, 5, 6, 1, 3]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is not sorted.

Now, the original list is shuffled, and the sorted() function provides a sorted version for comparison, demonstrating that the original list remains unchanged.

Summary

In this lab, you learned how to convert a list to a set in Python, effectively removing duplicate elements. Sets are unordered collections, so the order of elements may change during the conversion.

You also started learning how to convert a set back into a list and check if the resulting list is sorted. This involves using the list() function and comparing the sorted list with the original list.