How to check if a list is in descending order in Python

Python | Check if list is sorted or not

The sorted operation of list is essential operation in many application. But it takes best of O[nlogn] time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default sorted or not, one can check if list is sorted or not. Lets discuss various ways this can be achieved.

Method #1 : Naive method
The simplest way to check this is run a loop for first element and check if we could find any smaller element than it after that element, if yes, the list is not sorted.




# Python3 code to demonstrate
# to check if list is sorted
# using naive method
# initializing list
test_list = [1, 4, 5, 8, 10]
# printing original list
print ["Original list : " + str[test_list]]
# using naive method to
# check sorted list
flag = 0
i = 1
while i < len[test_list]:
if[test_list[i] < test_list[i - 1]]:
flag = 1
i += 1
# printing result
if [not flag] :
print ["Yes, List is sorted."]
else :
print ["No, List is not sorted."]

Output :

Original list : [1, 4, 5, 8, 10] Yes, List is sorted.

Method #2 : Using sort[]
The new list can be made as a copy of the original list, sorting the new list and comparing with the old list will give us the result if sorting was required to get sorted list or not.




# Python3 code to demonstrate
# to check if list is sorted
# using sort[]
# initializing list
test_list = [10, 4, 5, 8, 10]
# printing original list
print ["Original list : " + str[test_list]]
# using sort[] to
# check sorted list
flag = 0
test_list1 = test_list[:]
test_list1.sort[]
if [test_list1 == test_list]:
flag = 1
# printing result
if [flag] :
print ["Yes, List is sorted."]
else :
print ["No, List is not sorted."]

Output :



Original list : [10, 4, 5, 8, 10] No, List is not sorted.

Method #3 : Using sorted[]
Using the similar analogy as the above method, but does not create a new space, but just a momentary space for that time and hence useful, shorter and faster method than above.




# Python3 code to demonstrate
# to check if list is sorted
# using sorted[]
# initializing list
test_list = [1, 4, 5, 8, 10]
# printing original list
print ["Original list : " + str[test_list]]
# using sorted[] to
# check sorted list
flag = 0
if[test_list == sorted[test_list]]:
flag = 1
# printing result
if [flag] :
print ["Yes, List is sorted."]
else :
print ["No, List is not sorted."]

Output :

Original list : [1, 4, 5, 8, 10] Yes, List is sorted.

Method #4 : Using all[]
Most elegant, pythonic and faster way to check for sorted list is the use of all[]. This uses the similar method as naive, but use of all[] make it quicker.




# Python3 code to demonstrate
# to check if list is sorted
# using all[]
# initializing list
test_list = [9, 4, 5, 8, 10]
# printing original list
print ["Original list : " + str[test_list]]
# using all[] to
# check sorted list
flag = 0
if[all[test_list[i] >> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort[] >>> b [2, 3, 3, 6, 7, 8, 9] # Sorted!

Custom Arguments

To customize how the sort[] method works, you can pass two optional arguments:

  • Key
  • Reverse

Let's see how they change the behavior of this method. Here we have a method call with these two arguments:

Before explaining how they work, I would like to explain something that you probably noticed in the diagram above – in the method call, the names of the parameters have to be included before their corresponding values, like this:

  • key=
  • reverse=

This is because they are keyword-only arguments. If you are passing a custom value for them, their names have to be specified in the method call, followed by an equal sign = and their corresponding values, like this:

Otherwise, if you try to pass the arguments directly as we normally do for positional parameters, you will see this error because the function will not know which argument corresponds to which parameter:

TypeError: sort[] takes no positional arguments

Reverse

Now that you know what keyword-only arguments are, let's start with reverse.

The value of reverse can be either True or False:

  • False means that the list will be sorted in ascending order.
  • True means that the list will be sorted in descending [reverse] order.

💡 Tip: By default, its value is False – if you don't pass any arguments for this parameter, the list is sorted in ascending order.

Here we have a few examples:

By default, reverse is False# List of Integers >>> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort[] >>> b [2, 3, 3, 6, 7, 8, 9] # List of Strings >>> c = ["A", "Z", "D", "T", "U"] >>> c.sort[] >>> c ['A', 'D', 'T', 'U', 'Z']

💡 Tip: If the elements of the list are strings, they are sorted alphabetically.

To specify that reverse is True, so the list has to be sorted in descending [reverse] order.# List of Integers >>> b = [6, 3, 8, 2, 7, 3, 9] >>> b.sort[reverse=True] >>> b [9, 8, 7, 6, 3, 3, 2] # List of Strings >>> c = ["A", "Z", "D", "T", "U"] >>> c.sort[reverse=True] >>> c ['Z', 'U', 'T', 'D', 'A']

💡 Tip: Notice how the list is sorted in descending order if reverse is True.

Key

Now that you know how to work with the reverse parameter, let's see the key parameter.

This parameter is a little bit more detailed because it determines how the elements of the list are be compared during the sorting process.

Basic Syntax

The value of key is either:

  • None, which means that the elements of the list will be compared directly. For example, in a list of integers, the integers themselves can be used for the comparison.
  • A function of one argument that generates an intermediate value for each element. This intermediate value is calculated only once and it's used to make the comparisons during the entire sorting process. We use this when we don't want to compare the elements directly, for example, when we want to compare strings based on their length [the intermediate value].

💡 Tip: By default, the value of key is None, so the elements are compared directly.

For example:

Let's say that we want to sort a list of strings based on their length, from the shortest string to the longest string. We can pass the function len as the value of key, like this:

>>> d = ["aaa", "bb", "c"] >>> d.sort[key=len] >>> d ['c', 'bb', 'aaa']

💡 Tip: Notice that we are only passing the name of the function [len] without parenthesis because we are not calling the function. This is very important.

Notice the difference between comparing the elements directly and comparing their length [see below]. Using the default value of key [None] would have sorted the strings alphabetically [left], but now we are sorting them based on their length [right]:

What happens behind the scenes? Each element is passed as an argument to the len[] function, and the value returned by this function call is used to perform the comparisons during the sorting process:

This results in a list with a different sorting criteria: length.

Here we have another example:

Another interesting example is sorting a list of strings as if they were all written in lowercase letters [for example, making "Aa" equivalent to "aa"].

According to lexicographical order, capital letters come before lowercase letters:

>>> "E" < "e" True

So the string "Emma" would come before "emily" in a sorted list, even if their lowercase versions would be in the opposite order:

>>> "Emma" < "emily" True >>> "emma" < "emily" False

To avoid distinguishing between capital and lowercase letters, we can pass the function str.lower as key. This will generate a lowercase version of the strings that will be used for the comparisons:

>>> e = ["Emma", "emily", "Amy", "Jason"] >>> e.sort[key=str.lower] >>> e ['Amy', 'emily', 'Emma', 'Jason']

Notice that now, "emily" comes before "Emma" in the sorted list, which is exactly what we wanted.

💡 Tip: if we had used the default sorting process, all the strings that started with an uppercase letter would have come before all the strings that started with a lowercase letter:

>>> e = ["Emma", "emily", "Amy", "Jason"] >>> e.sort[] >>> e ['Amy', 'Emma', 'Jason', 'emily']

Here is an example using Object-Oriented Programming [OOP]:

If we have this very simple Python class:

>>> class Client: def __init__[self, age]: self.age = age

And we create four instances:

>>> client1 = Client[67] >>> client2 = Client[23] >>> client3 = Client[13] >>> client4 = Client[35]

We can make a list that references them:

>>> clients = [client1, client2, client3, client4]

Then, if we define a function to get the age of these instances:

>>> def get_age[client]: return client.age

We can sort the list based on their age by passing the get_age function an an argument:

>>> clients.sort[key=get_age]

This is the final, sorted version of the list. We use a for loop to print the age of the instances in the order that they appear in the list:

>>> for client in clients: print[client.age] 13 23 35 67

Exactly what we wanted – now the list is sorted in ascending order based on the age of the instances.

💡 Tip: Instead of defining a get_age function, we could have used a lambda function to get the age of each instance, like this:

>>> clients.sort[key=lambda x: x.age]

Lambda functions are small and simple anonymous functions, which means that they don't have a name. They are very helpful for these scenarios when we only want to use them in particular places for a very short period of time.

This is the basic structure of the lambda function that we are using to sort the list:

Basic Structure of a Lambda Function

Passing Both Arguments

Awesome! Now you know to customize the functionality of the sort[] method. But you can take your skills to a whole new level by combining the effect of key and reverse in the same method call:

>>> f = ["A", "a", "B", "b", "C", "c"] >>> f.sort[key=str.lower, reverse=True] >>> f ['C', 'c', 'B', 'b', 'A', 'a']Sort the list in reverse order as if the strings were in all lowercase.

These are the different combinations of the arguments and their effect:

The Order of Keyword-Only Arguments Doesn't Matter

Since we are specifying the names of the arguments, we already know which value corresponds to which parameter, so we can include either key or reverse first in the list and the effect will be exactly the same.

So this method call:

Is equivalent to:

This is an example:

>>> a = ["Zz", "c", "y", "o", "F"] >>> a.sort[key=str.lower, reverse=True] >>> a ['Zz', 'y', 'o', 'F', 'c']

If we change the order of the arguments, we get the exact same result:

>>> a = ["Zz", "c", "y", "o", "F"] >>> a.sort[reverse=True, key=str.lower] >>> a ['Zz', 'y', 'o', 'F', 'c']

Video liên quan

Bài mới nhất

Chủ Đề