How to Check If a List Is Sorted (Any Order) in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a list is sorted in Python, regardless of whether it's in ascending or descending order. You'll explore the fundamentals of sorted lists and how they are used in various programming tasks.

The lab guides you through creating and manipulating lists using Python's built-in functions. You'll learn how to use the sorted() function to create new sorted lists from existing ones, both in ascending and descending order. The lab also demonstrates how to sort lists of strings.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/lists("Lists") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559535{{"How to Check If a List Is Sorted (Any Order) in Python"}} python/for_loops -.-> lab-559535{{"How to Check If a List Is Sorted (Any Order) in Python"}} python/lists -.-> lab-559535{{"How to Check If a List Is Sorted (Any Order) in Python"}} python/build_in_functions -.-> lab-559535{{"How to Check If a List Is Sorted (Any Order) in Python"}} python/data_collections -.-> lab-559535{{"How to Check If a List Is Sorted (Any Order) in Python"}} end

Explore Sorted Lists

In this step, you will learn about sorted lists in Python. Sorted lists are fundamental in programming for tasks like searching, data analysis, and algorithm optimization. Python provides built-in functions and methods to easily create and manipulate sorted lists.

First, let's create a simple list of numbers:

## Create a list of numbers
numbers = [5, 1, 4, 2, 8]
print(numbers)

Save the above code in a file named sort_list.py in your ~/project directory. You can use the VS Code editor to create this file.

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

python ~/project/sort_list.py

You should see the original list printed:

[5, 1, 4, 2, 8]

To sort this list, you can use the sorted() function. The sorted() function returns a new sorted list from the items in iterable.

## Create a list of numbers
numbers = [5, 1, 4, 2, 8]

## Sort the list using the sorted() function
sorted_numbers = sorted(numbers)

## Print the sorted list
print(sorted_numbers)

Modify your sort_list.py file to include the above code. Then, run the script again:

python ~/project/sort_list.py

Now, you should see the sorted list printed:

[1, 2, 4, 5, 8]

Note that the original numbers list remains unchanged. The sorted() function creates a new sorted list.

If you want to sort the list in descending order, you can use the reverse parameter:

## Create a list of numbers
numbers = [5, 1, 4, 2, 8]

## Sort the list in descending order
sorted_numbers = sorted(numbers, reverse=True)

## Print the sorted list
print(sorted_numbers)

Modify your sort_list.py file to include the above code. Then, run the script again:

python ~/project/sort_list.py

You should see the sorted list in descending order:

[8, 5, 4, 2, 1]

You can also sort lists of strings:

## Create a list of strings
names = ["Alice", "Bob", "Charlie", "David"]

## Sort the list of strings
sorted_names = sorted(names)

## Print the sorted list
print(sorted_names)

Modify your sort_list.py file to include the above code. Then, run the script again:

python ~/project/sort_list.py

You should see the sorted list of names:

['Alice', 'Bob', 'Charlie', 'David']

The strings are sorted alphabetically.

Check Ascending or Descending

In this step, you will learn how to check if a list is sorted in ascending or descending order. This is a common task in many programming scenarios, such as data validation and algorithm design.

To determine if a list is sorted, you can iterate through the list and compare adjacent elements. If each element is less than or equal to the next element, the list is sorted in ascending order. If each element is greater than or equal to the next element, the list is sorted in descending order.

Let's start by creating a Python script named check_order.py in your ~/project directory using the VS Code editor.

Here's the code to check if a list is sorted in ascending order:

def is_ascending(lst):
    for i in range(len(lst) - 1):
        if lst[i] > lst[i + 1]:
            return False
    return True

numbers = [1, 2, 3, 4, 5]
print(is_ascending(numbers))

numbers = [1, 3, 2, 4, 5]
print(is_ascending(numbers))

Save the above code in check_order.py. Now, run the script using the following command:

python ~/project/check_order.py

You should see the following output:

True
False

The first list [1, 2, 3, 4, 5] is sorted in ascending order, so the function returns True. The second list [1, 3, 2, 4, 5] is not sorted in ascending order, so the function returns False.

Now, let's add code to check if a list is sorted in descending order:

def is_descending(lst):
    for i in range(len(lst) - 1):
        if lst[i] < lst[i + 1]:
            return False
    return True

numbers = [5, 4, 3, 2, 1]
print(is_descending(numbers))

numbers = [5, 2, 3, 2, 1]
print(is_descending(numbers))

Add the above code to your check_order.py file. The complete check_order.py file should look like this:

def is_ascending(lst):
    for i in range(len(lst) - 1):
        if lst[i] > lst[i + 1]:
            return False
    return True

def is_descending(lst):
    for i in range(len(lst) - 1):
        if lst[i] < lst[i + 1]:
            return False
    return True

numbers = [1, 2, 3, 4, 5]
print(is_ascending(numbers))

numbers = [1, 3, 2, 4, 5]
print(is_ascending(numbers))

numbers = [5, 4, 3, 2, 1]
print(is_descending(numbers))

numbers = [5, 2, 3, 2, 1]
print(is_descending(numbers))

Run the script again:

python ~/project/check_order.py

You should see the following output:

True
False
True
False

The list [5, 4, 3, 2, 1] is sorted in descending order, so the function returns True. The list [5, 2, 3, 2, 1] is not sorted in descending order, so the function returns False.

This exercise demonstrates how to check if a list is sorted in ascending or descending order using Python.

Use sorted() for Comparison

In this step, you will learn how to use the sorted() function to compare two lists. Comparing lists is a common task in programming, especially when you need to verify if two sets of data are identical or if one list is a subset of another.

The sorted() function can be used to sort both lists before comparing them. This ensures that the order of elements does not affect the comparison result.

Let's create a Python script named compare_lists.py in your ~/project directory using the VS Code editor.

Here's the code to compare two lists using the sorted() function:

def compare_lists(list1, list2):
    sorted_list1 = sorted(list1)
    sorted_list2 = sorted(list2)
    if sorted_list1 == sorted_list2:
        return True
    else:
        return False

list_a = [3, 1, 2]
list_b = [1, 2, 3]
print(compare_lists(list_a, list_b))

list_c = [3, 1, 2]
list_d = [1, 2, 4]
print(compare_lists(list_c, list_d))

Save the above code in compare_lists.py. Now, run the script using the following command:

python ~/project/compare_lists.py

You should see the following output:

True
False

The lists list_a and list_b contain the same elements, so the function returns True. The lists list_c and list_d do not contain the same elements, so the function returns False.

Let's consider another example with strings:

def compare_lists(list1, list2):
    sorted_list1 = sorted(list1)
    sorted_list2 = sorted(list2)
    if sorted_list1 == sorted_list2:
        return True
    else:
        return False

list_e = ["apple", "banana", "cherry"]
list_f = ["cherry", "apple", "banana"]
print(compare_lists(list_e, list_f))

list_g = ["apple", "banana", "cherry"]
list_h = ["apple", "banana", "date"]
print(compare_lists(list_g, list_h))

Add the above code to your compare_lists.py file. The complete compare_lists.py file should look like this:

def compare_lists(list1, list2):
    sorted_list1 = sorted(list1)
    sorted_list2 = sorted(list2)
    if sorted_list1 == sorted_list2:
        return True
    else:
        return False

list_a = [3, 1, 2]
list_b = [1, 2, 3]
print(compare_lists(list_a, list_b))

list_c = [3, 1, 2]
list_d = [1, 2, 4]
print(compare_lists(list_c, list_d))

list_e = ["apple", "banana", "cherry"]
list_f = ["cherry", "apple", "banana"]
print(compare_lists(list_e, list_f))

list_g = ["apple", "banana", "cherry"]
list_h = ["apple", "banana", "date"]
print(compare_lists(list_g, list_h))

Run the script again:

python ~/project/compare_lists.py

You should see the following output:

True
False
True
False

This example demonstrates how to use the sorted() function to compare lists of strings.

Summary

In this lab, you explored sorted lists in Python and learned how to use the sorted() function to create new sorted lists from existing lists. You saw how to sort a list of numbers in ascending order and descending order using the reverse parameter.

The lab demonstrated how the original list remains unchanged when using sorted(), as it returns a new sorted list. You also learned that sorted() can be applied to lists of strings, although the provided content was truncated before demonstrating this.