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.