Which list is used to present a list in the descending order.

Python List sort()

In this tutorial, we will learn about the Python sort() method with the help of examples.

The sort() method sorts the elements of a given list in a specific ascending or descending order.

Example

prime_numbers = [11, 3, 7, 5, 2]
# sort the list prime_numbers.sort()
print(prime_numbers) # Output: [2, 3, 5, 7, 11]

🔹 Purpose and Use Cases

With the sort() method, you can sort a list in either:

  • Ascending Order
  • Descending Order

This method is used to sort a list in place, which means that it mutates it or modifies it directly without creating additional copies, so remember:

You will learn more about mutation in this article (I promise!), but for now it's very important that you know that the sort() method modifies the list, so its original version is lost.

Because of this, you should only use this method if:

  • You want to modify (sort) the list permanently.
  • You don't need to keep the original version of the list.

If this fits your needs, then the .sort() method is exactly what you are looking for.

🔸 Syntax and Arguments

Let's see how you can call .sort() to take advantage of its full power.

This is the most basic call (with no arguments):

If you don't pass any arguments, by default:

  • The list will be sorted in ascending order.
  • The elements of the list will be compared directly using their values with the < operator.

For example:

>>> 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=<f>
  • reverse=<value>

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']

What is the sort() method in Python?

This method takes a list and sorts it in place. This method does not have a return value.

In this example, we have a list of numbers and we can use the sort() method to sort the list in ascending order.

my_list = [67, 2, 999, 1, 15] # this prints the unordered list print("Unordered list: ", my_list) # sorts the list in place my_list.sort() # this prints the ordered list print("Ordered list: ", my_list)

If the list is already sorted then it will return None in the console.

my_list = [6, 7, 8, 9, 10] # this will return None because the list is already sorted print(my_list.sort())

The sort() method can take in two optional arguments called key and reverse.

key has the value of a function that will be called on each item in the list.

In this example, we can use the len() function as the value for the key argument. key=len will tell the computer to sort the list of names by length from smallest to largest.

names = ["Jessica", "Ben", "Carl", "Jackie", "Wendy"] print("Unsorted: ", names) names.sort(key=len) print("Sorted: ", names)

reverse has a boolean value of True or False.

In this example, reverse=True will tell the computer to sort the list in reverse alphabetical order.

names = ["Jessica", "Ben", "Carl", "Jackie", "Wendy"] print("Unsorted: ", names) names.sort(reverse=True) print("Sorted: ", names)

Python List sort() - Sorts Ascending or Descending List

The list.sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items.

Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.

Syntax:

list.sort(key=None, reverse=False)

Parameters:

  1. key: (Optional) A function that extracts a comparison key from each list element while sorting.
  2. reverse: (Optional) If true, the sorted list will be reversed. By default, it is False.

Return Value:

No return value. It sorts the list itself.

The following example demonstrates the sort() function on numeric lists.

Example: Sort Numeric List
Copy
nums = [1, 5, 3, 4, 2, 10, 6, 8, 7, 9] nums.sort() print('List in Ascending Order: ', nums) nums.sort(reverse=True) print('List in Descending Order: ', nums)
Output
List in Ascending Order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] List in Descending Order: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

The sort() method can also be used on character lists.

Example: Sort Char List
Copy
al = ['a','d','e','c','b'] al.sort(reverse=True) print('List in Descending Order: ', al) al.sort() print('List in Ascending Order: ', al)
Output
List in Descending Order: ['e', 'd', 'c', 'b', 'a'] List in Ascending Order: ['a', 'b', 'c', 'd', 'e']

The following example sorts the string list in alphabetical order.

Example: Sort String List
Copy
cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.sort() print('List in Ascending Order: ', cities) cities.sort(reverse=True) print('List in Descending Order: ', cities)
Output
List in Ascending Order: ['London', 'Mumbai', 'New York', 'Paris'] List in Descending Order: ['Paris', 'New York', 'Mumbai', 'London']

Sort lists of list in descending order according to the length of each lists

I have a list in the following format. I want to sort my list in decreasing order according to the length of each list.
mylist:
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
+ 6/9453 vertices, named:
[1] VEGFA EPHB2 GRIN2B AP2M1 KCNJ11 ABCC8
[[1]][[2]]
[[1]][[2]][[1]]
+ 4/9453 vertices, named:
[1] VEGFA VTN PRKCA ADCY5
[[1]][[3]]
[[1]][[3]][[1]]
+ 0/9453 vertices, named:
[[1]][[4]]
[[1]][[4]][[1]]
+ 4/9453 vertices, named:
[1] VEGFA KDR GRB2 ADRB1
[[1]][[5]]
[[1]][[5]][[1]]
+ 3/9453 vertices, named:
[1] VEGFA AKT1 AKT2
[[1]][[6]]
[[1]][[6]][[1]]
+ 4/9453 vertices, named:
[1] VEGFA CTGF AP3D1 AP3S2
[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
+ 6/9453 vertices, named:
[1] HHEX EFEMP2 TP53 ARIH2 ENSA ABCC8
[[2]][[2]]
[[2]][[2]][[1]]
+ 5/9453 vertices, named:
[1] HHEX TLE1 POLB PRKCA ADCY5
[[2]][[3]]
[[2]][[3]][[1]]
+ 0/9453 vertices, named:
[[2]][[4]]
[[2]][[4]][[1]]
+ 5/9453 vertices, named:
[1] HHEX TLE1 ATN1 MAGI2 ADRB1
[[2]][[5]]
[[2]][[5]][[1]]
+ 4/9453 vertices, named:
[1] HHEX JUN ESR1 AKT2
[[2]][[6]]
[[2]][[6]][[1]]
+ 6/9453 vertices, named:
[1] HHEX TLE1 CDK1 BUB1 AP3B1 AP3S2
[[3]]
[[3]][[1]]
[[3]][[1]][[1]]
+ 7/9453 vertices, named:
[1] PPP1R3A RPS6KA1 MAPK1 TP53 ARIH2 ENSA ABCC8
[[3]][[2]]
[[3]][[2]][[1]]
+ 4/9453 vertices, named:
[1] PPP1R3A PLN PRKACA ADCY5
[[3]][[3]]
[[3]][[3]][[1]]
+ 0/9453 vertices, named:
[[3]][[4]]
[[3]][[4]][[1]]
+ 4/9453 vertices, named:
[1] PPP1R3A RPS6KA1 GRB2 ADRB1
[[3]][[5]]
[[3]][[5]][[1]]
+ 4/9453 vertices, named:
[1] PPP1R3A RPS6KA1 PDPK1 AKT2
[[3]][[6]]
[[3]][[6]][[1]]
+ 6/9453 vertices, named:
[1] PPP1R3A RPS6KA1 MAPK1 IRS1 AP3S1 AP3S2
where "+ 6/9453" indicating the length of that list.For component 1 there are six list of different length, so i want to sort all the component list in decreasing order. The zero length element is not to be considered.
I used one command i don't know is it right way to do it.
mylist[sort(order(mylist))]
Error: unexpected ']' in "mylist[sort(order(mylist))]"
Thanks.
Sorting
Systems Bioinformatics
Data Integration

Sort a List in Descending Order in Python

Python Python List

Created: April-23, 2021 | Updated: July-13, 2021

This tutorial demonstrates how to sort a list in descending order in Python.

Python Advanced List Tutorial

Python Advanced List includes the following concepts.

Let’s explore each of them in detail with examples.

#1) Python Sort List

The sort() method is used to sort the elements in a specific order i.e. Ascending or Descending.

If you want to sort the elements in Ascending order, then you can use the following syntax.

list.sort()

If you want to sort the elements in Descending order, then you can use the following syntax.

list.sort(reverse=True)

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.sort() print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]

Now let’s see, How to sort the list in a Descending Order.

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.sort() print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]

Thus sort() method is used to arrange a list in either Ascending or Descending order. One more important thing to remember here is that sort() method changes the order of the list permanently. If you want to change the order of the list temporarily, then you need to use sorted() function.

#2) Sorted function

In order to maintain the original order of the list that is present in sorted order, you can use the sorted() function. The sorted() function allows you to display your list in a particular order, without affecting the actual order of the list.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] print(sorted(Students)) print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]
[‘Harsh’, ‘Andrew’, ‘Danny’]

As you can see from the output, the original order of the list remains intact.

You can also print the list in a reverse order using the sorted function in the following manner:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] print(sorted(Students)) print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]
[‘Harsh’, ‘Andrew’, ‘Danny’]

#3) Python Reverse List

In order to reverse the original order of a list, you can use the reverse() method. The reverse() method is used to reverse the sequence of the list and not to arrange it in a sorted order like the sort() method.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny'] Students.reverse() print(Students)

Output:

[‘Danny’, ‘Andrew’, ‘Harsh’]

reverse() method reverses the sequence of the list permanently. Hence in order to get back to the original sequence of the list apply the reverse() method again to the same list.

#4) Python List Index

Index method is used to find a given element in the list and return to its position.

If the same element is present more than once, then it returns the position of the first element. The index in python starts from 0.

Example:

Input:

Students = ['Harsh','Andrew','Danny','Ritesh','Meena'] print(Students.index('Danny'))

Output:

2

Screenshot:

If you search for an element which is not present in the list, then You will get an error.

Input:

Students = ['Harsh','Andrew','Danny','Ritesh','Meena'] print(Students.index('Vammy'))

Output:

Value Error: ‘Vammy’ is not in the list

#5) Python Copy List

At times, You may want to start with an existing list and make an entirely new list based on the first one.

Now, let’s explore how copying a list works and also examine a situation where copying a list is useful.

In order to copy a list, you can make a slice that includes the complete original list by omitting the first index and the second index ([:]). This, in turn, will tell Python to make a slice that starts at the first item and ends with the last item, by producing a copy of the entire list.

For Example, imagine we have a list of our favorite foods and we want to make a separate list of foods that a friend likes. This friend likes everything in our list so far, so we can create that list by copying ours.

Input:

my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods)

Output:

My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]

My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]

Screenshot:

First, we create a list of the foods we like called my_foods. Then we make a new list called friend_foods. Later, we make a copy of my_foods by asking for a slice of my_foods without specifying any indices and store the copy in friend_foods. When we print each list, we see that they both contain the same foods.

To prove that we actually have two separate lists, we’ll add new food to each list and show that each list keeps track of the appropriate person’s favorite foods:

Input:

my_foods = ['pizza', 'falafel', 'carrot cake'] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods)

Output:

My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]

My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]

#6) Python Join List

Python join list means concatenating a list of strings to form a string. Sometimes it’s useful when you have to convert a list to string. For Example, convert a list to a comma separated string to save in a file.

Let’s understand this with an Example:

Input:

my_foods = ['pizza', 'falafel', 'carrot cake'] my_foods_csv=",".join(my_foods) print("my favorite foods are:",my_foods_csv)

Output:

my favorite foods are: pizza,falafel,carrot cake

In the above example, you can see that we have the my_foods list which we have appended in a string variable named as my_foods_csv using the join function.

Finally, we print my_foods_csv string.

#7) Python Sum List function

Python provides an in-built function called sum() which sums up the numbers in the list.

Example:

Input:

numbers = [4,6,8,9,3,7,2] Sum = sum(numbers) print(Sum)

Output:

39

In the above example, we have taken a list of numbers and using the sum function we have added all the numbers.

#8) Python Remove Duplicates from the List

As you know, a list can contain duplicates. But in case, if you want to remove the duplicate from a list, how can you do it?

The simple way is to convert the list to the dictionary using the list item as keys. This will automatically remove any duplicates as dictionaries cannot have duplicate keys and all the items in the list will tend to appear in correct order.

Example:

Input:

numbers = [4,6,8,9,3,7,2] Sum = sum(numbers) print(Sum)

Output:

39

In the above example we have a list with duplicate elements and from that, we have created a dictionary, Again we have created a list out of that dictionary, and finally, we get a list without any duplicates.

Creating a unique list from the list having duplicate elements is another way to remove duplicates from a list.

We can do it in the following manner:

Input:

mylist = [4, 5, 6, 5, 4] uniqueList = [] <strong>for</strong> elem in mylist: <strong>if</strong> elem not in uniqueList: uniqueList.append(elem) print(uniqueList)

Output:

[4, 5, 6]

In the above example, we have created a unique list and then appended the unique items from the list to another list.

#9) List Comprehension

If you want to create a list which contains the squares of numbers from 1 to 10, then you can do it using for-loop.

Example:

Input:

squares = [] <strong>for</strong> value in range(1,11): square = value**2 squares.append(square) print(squares)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The above process takes 3 to 4 lines of code. But using List comprehension it can be accomplished in just one line of code.

Input:

squares = [value**2 <strong>for</strong> value in range(1,11)] print(squares)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the above example, we begin with a descriptive name for the list i.e. squares. Next, we open a set of square brackets and define the expression for the values that we want to store in the new list. In this example, the expression value that raises the value to the second power is **2.

Then, write a for loop to generate the numbers you want to feed into the expression and close the square brackets. The for loop in this example is for the value in the range(1,11), which feeds the values 1 through 10 into the expression value**2.

Note: No colon is used at the end of the for statement.

Sample Programs

Write a program to sort the list of cricket players according to their names.

#Create a List Cricket_Players = ['Sourav', 'Rahul','Sachin','Mahender','Virat','Shikhar','Harbhajan'] #Print Original List print("Original List:") print(Cricket_Players) #Sort the List Cricket_Players.sort() #Print Sorted List print("Sorted List:") print(Cricket_Players)

Write a program to reverse the list of cell phone vendors.

#Create a List CellPhone_Vendors = ['Nokia','Samsung','Xiomi','Apple','Motorola'] #Print Original List print("Original List:") print(CellPhone_Vendors) #Reverse the List CellPhone_Vendors.reverse() #Print Reversed List print("Reversed List:") print(CellPhone_Vendors)

Write a program to remove duplicates from the list of students participating in the sports day.

#Create a List Student_Players = ['Reyan','Vicky','Mark','Steve','Mark','Reyan','Vijay'] #Print Original List print("Original List:") print(Student_Players) #Create an empty list unique_List=[] #Append unique elements from list to empty list <strong>for</strong> student in Student_Players: <strong>if</strong> student not in unique_List: unique_List.append(student) #Print new list print("Unique List:") print(unique_List)

Write a program to demonstrate sort, reverse and finding the index of the element in a list containing numbers.

#Create a Sorted list my_list = [7, 8, 3, 6, 2, 8, 4] #Find the index of element in a list print(my_list.index(8)) #Sort the list my_list.sort() #Print the sorted list print(my_list) #Reverse the list my_list.reverse() #Print the reversed list print(my_list)

Conclusion

From this tutorial, we learned how to perform various operations on a list using different methods and functions.

We can conclude this tutorial using the below pointers:

  • Sort method is used to sort the list permanently.
  • The sorted function is used to present the list in sorted order. However, the original sequence of the list remains unchanged.
  • Reverse method is used to reverse the order of the list.
  • Sum() function is used to sum the elements in the list.
  • You can remove the duplicate elements in the list by converting a list to a dictionary or by creating a new list and using for loop and if condition to append only the unique elements.
  • List comprehension can be used to reduce the lines of code to create a specific type of list.
  • Java List Methods - Sort List, Contains, List Add, List Remove
  • Common Python List Methods With Syntax And Examples
  • Python Variables
  • Top 6 BEST Python Testing Frameworks [Updated 2022 List]
  • Python String Functions - Tutorial With Examples
  • Java List - How To Create, Initialize & Use List In Java
  • Bootstrap List Group Tutorial With Code Examples
  • Python Tuple Tutorial with Hands-on Examples

<ol>: The Ordered List element

The <ol> HTML element represents an ordered list of items — typically rendered as a numbered list.

Content categoriesFlow content, and if the <ol> element's children include at least one <li> element, palpable content.
Permitted contentZero or more <li>, <script> and <template> elements.
Tag omissionNone, both the starting and ending tag are mandatory.
Permitted parentsAny element that accepts flow content.
Implicit ARIA rolelist
Permitted ARIA rolesdirectory, group, listbox, menu, menubar, none, presentation, radiogroup, tablist, toolbar, tree
DOM interfaceHTMLOListElement