Check with all() and zip()
In this step, you will learn how to use the all()
and zip()
functions to check if a list is sorted. These functions provide a concise and efficient way to verify the order of elements in a list.
First, let's understand the zip()
function. The zip()
function takes multiple iterables (e.g., lists) as input and returns an iterator of tuples, where each tuple contains the corresponding elements from the input iterables.
Consider the following example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
zipped = zip(list1, list2)
print(list(zipped))
Add this code to your sort_list.py
file, replacing the previous content. Then, run the script:
python sort_list.py
You should see the following output:
[(1, 4), (2, 5), (3, 6)]
The zip()
function has created an iterator that yields tuples containing corresponding elements from list1
and list2
.
Now, let's understand the all()
function. The all()
function takes an iterable as input and returns True
if all elements in the iterable are true, and False
otherwise.
Consider the following example:
bool_list = [True, True, True]
print(all(bool_list))
bool_list = [True, False, True]
print(all(bool_list))
Add this code to your sort_list.py
file and run it:
python sort_list.py
You will see the following output:
True
False
Now, let's combine zip()
and all()
to check if a list is sorted. The idea is to compare each element with the next element in the list and check if the list is in ascending order.
numbers = [1, 2, 3, 4, 5]
is_sorted = all(numbers[i] <= numbers[i+1] for i in range(len(numbers)-1))
print(is_sorted)
numbers = [1, 2, 5, 4, 5]
is_sorted = all(numbers[i] <= numbers[i+1] for i in range(len(numbers)-1))
print(is_sorted)
Modify your sort_list.py
file to include this code. Run the script again:
python sort_list.py
You should see the following output:
True
False
This code uses a generator expression with zip()
to compare adjacent elements in the list. The all()
function then checks if all the comparisons are true, indicating that the list is sorted.
This approach provides a concise and efficient way to check if a list is sorted in Python.