Python sort list [2 Methods and 8 Examples]

 

Introduction to Python sort list

Python Sort list is the process of arranging data into meaningful order so that we can analyze it more effectively. In python, there are many algorithms to sort data in ascending or descending order. In this article, we will learn how we can sort python lists in ascending or descending order. A list can contain any kind of data including strings, integers, dictionaries, dates, nested lists, and many more.

We will learn how we can sort a list that contains different data types elements. We will mainly cover two different built-in methods that are used to sort the list in python which are sort() and sorted() methods. We will see the basic syntax of these methods and the difference between them. We will also cover how we can use these methods to arrange the list in ascending or descending order. In a nutshell, this tutorial will contain all the necessary information and examples that are needed to start working with the python sort list.

Advertisement

 

Getting started with Python sort list

  • A standard order is called the ascending order: a to z, 0 to 9.
  • The reverse order is called the descending order: z to a, 9 to 0. For dates and times, ascending means that earlier values precede later ones.
  • Python has two basic functions for sorting lists: <strong>sort()</strong> and sorted() method.
  • The sort() method sorts the list in place, while the sorted() method returns a new sorted list from the items in iterable.
  • Both functions have the same options: key and reverse.
  • The key takes a function that will be used on each value in the list being sorted to determine the resulting order.
  • The reverse option can reverse the comparison order.

In this section, we will see the basic syntax of these python sort list methods and will highlight some of the differences between these methods.

 

Syntax of Python sort and sorted function

The syntax of the python sort and sorted method is very much similar. But there is a difference in the returned value of these functions. See the syntax of the python sort() method below:

list_name.sort(key=..., reverse=...)

By default, the sort() method does not require any parameters, however, it has two optional parameters; key and reverse. The reverse will return the reversed list or the descending order of the list if it is equalized to true. While the key serves as a key for the sort comparison. Remember one thing that the sort() method doesn't return any value. Rather, it changes the original list.

While the sorted() method returns a new list in sorted form ( ascending or descending order). The simple syntax of python sorted() method is as follows:

sorted(list_name, key=..., reverse=...)

Notice that the sorted() method takes the list as an argument and returns a new sorted list.

 

Examples of Python sort list using sort() method

We had already discussed the syntax of the python sort() method. It is a built-in function that sorts a given list ( either in ascending or descending order). In this section, we will take various examples of different data typed lists and will sort them using this method. See the following examples.

Advertisement

 

Example-1: Python sort list of strings using sort() method

Let us now take the example of a list that contains strings elements in random order. We will apply the sort() method to arrange the list of strings in ascending order. See the example below:

# creating list of strings
mylist = ['b', 'r', 'p', 'a', 't', 'd']

# python sort list using sort() method
mylist.sort()

# printing list
print(mylist)

Output:

['a', 'b', 'd', 'p', 'r', 't']

Notice that the sort() method changes the original list into a sorted one. Let us take one more example of a list containing string values and apply the sorting method. See the example below:

# creating list of strings
mylist = ['welcome', 'to', 'go', 'linux', 'cloud']

# python sort list using sort() method
mylist.sort()

# printing list
print(mylist)

Output:

['cloud', 'go', 'linux', 'to', 'welcome']

Notice that based on the first alphabet, the sort() method sorts the strings in ascending order.

 

Example-2: Python sort list of strings in reverse order using sort() method

In the above examples, we have seen that when we do not provide the reverse parameter to true, by default, the sort() method sorts the list in ascending order. So in order to sort the given list in descending order, we have to explicitly provide the argument reverse to true. See the example below:

# creating list of strings
mylist = ['b', 'r', 'd', 'p', 'a', 'o']

# python sort list using sort() method in reverse order
mylist.sort(reverse=True)

# printing list
print(mylist)

Output:

['r', 'p', 'o', 'd', 'b', 'a']

Notice that the sort() method sorts the original list in descending order when the reverse parameter was equalized to true.

Advertisement

 

Example-3: Python sort list of integers using sort() method

We know that list can contain different data typed elements. In this section, we will sort a list containing numeric values in ascending and descending order. See the example below:

# creating list of strings
mylist = [2, 1, 5, 4, 3, 8, 7, 9, 10]

# python sort list using sort() method
mylist.sort()

# printing list
print(mylist)

Output:

[1, 2, 3, 4, 5, 7, 8, 9, 10]

Notice that we successfully sorted the list of numeric values in ascending order. Now to sort the list in descending order, we have to provide the reverse argument to true. See the example below:

# creating list of strings
mylist = [2, 1, 5, 4, 3, 8, 7, 9, 10]

# python sort list using sort() method in reverse order
mylist.sort(reverse=True)

# printing list
print(mylist)

Output:

[10, 9, 8, 7, 5, 4, 3, 2, 1]

See in the above example that the reverse method had changed the order of the list in descending order.

 

Example-4: Python sort list of dictionaries using sort() method

A python dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. A list can contain dictionaries as well. Here we will see how we can sort the list of dictionaries using the sort() method.  See the example below:

# creating list of dictionaries
mylist = [{'name':"Bashir"}, {'name':"Alam"}, {'name':"erlan"}]

# python sort list using sort() method
mylist.sort(key=lambda e: e['name']) 

# printing sorted list
print(mylist)

Output:

[{'name': 'Alam'}, {'name': 'Bashir'}, {'name': 'erlan'}]

Notice in the above example that we have provided the key parameter to the sort() method which simply sorts the list based on the provided key value. We have used the lambda function in our example, you can learn more about it from the article on python lambda. If we will provide the reverse parameter, then the sort() will arrange the dictionaries in reverse order based on the provided key value. See the example below:

Advertisement
# creating list of dictionaries
mylist = [{'name':"Bashir"}, {'name':"Alam"}, {'name':"erlan"}]

# python sort list using sort() method in reverse order
mylist.sort(reverse=True, key=lambda e: e['name']) 

# printing sorted list
print(mylist)

Output:

[{'name': 'erlan'}, {'name': 'Bashir'}, {'name': 'Alam'}]

We already had discussed that the sort() method can take two optional parameters; key and reverse and in the above example, we have provided both parameters.

 

Example-5: Python sort list by the length of string using sort() method

The len() method is used in python to find the length of a string. In this section, we will use this method to find the length of strings and then will sort them in ascending and descending order based on their length. See the example below.

# creatin a function which returns the length of string
def word_len(string):
  # return the length of string
  return len(string)
# creating list of dictionaries
mylist = ["welcome", "to", "golinux", "cloud"]

# sorting the elements based on length
mylist.sort(key=word_len)

# printing the list
print(mylist)

Output:

['to', 'cloud', 'welcome', 'golinux']

Notice that the elements are arranged in order from the smallest length to the largest length. If we will provide the parameter reverse with True, then it will sort the strings in reverse order of the length. See the example.

# creatin a function which returns the length of string
def word_len(string):
  # return the length of string
  return len(string)

# creating list of dictionaries
mylist = ["welcome", "to", "golinux", "cloud"]

# sorting the elements based on length
mylist.sort(reverse=True,key=word_len)

# printing the list
print(mylist)

Output:

['welcome', 'golinux', 'cloud', 'to']

Notice that the output is in the reverse order based on the length of the strings.

 

Examples of Python sort list using sorted() method

We already had covered different examples using the python sort() method. In this section, we will take the various examples of different data typed lists and will sort them using the python sorted() method, which is a little bit different from the sort() method. See the examples below:

 

Example-1: Python sort list using sorted() method

We already had discussed that the sorted() method returns a new list in sorted form( either in ascending or descending order). Here we will take various lists containing different data typed elements and will sort them using the sorted() method. See the example below which sorts the list of strings.

# creating list of dictionaries
mylist = ["welcome", "to", "golinux", "cloud"]

# python sort list using sorted() method
sorted_list = sorted(mylist)

# printing the list
print(sorted_list)

Notice that the sorted() method did not change the original list, it created a new list which is the sorted form of the original list. We can apply the same method on a list containing numeric values as well. See the example below:

# creating list of dictionaries
mylist = [2, 4, 5, 3, 1, 8, 6, 7, 9, 10]

# python sort list using sorted() method
sorted_list = sorted(mylist)

# printing the list
print(sorted_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Notice that the sorted() method arranges the list in ascending order.

 

Example-2: Python sorted() method with reverse argument

The reverse parameter performs the same function as it was doing in sort() method. It will sort the list in reverse order. Let us take examples using reverse arguments to sort the list in descending order. See the example below:

# creating list of dictionaries
mylist = ["welcome", "to", "golinux", "cloud"]

# python sort list using sorted() method
sorted_list = sorted(mylist, reverse=True)

# printing the list
print(sorted_list)

Output:

['welcome', 'to', 'golinux', 'cloud']

Now let us apply the reverse method on a list containing numeric values. See the example below:

# creating list of dictionaries
mylist = [2, 4, 5, 3, 1, 8, 6, 7, 9, 10]

# python sort list using sorted() method
sorted_list = sorted(mylist, reverse=True)

# printing the list
print(sorted_list)

Output:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Notice that the reverse parameter arranged the newly created list in reverse order.

 

Example-3: Python sorted() method  with key parameter

The role of the key parameter is the same. It is used to specify the key for comparison to sort the elements. For example in the python program below, we will sort the list of strings based on their length by specifying the key parameter to be the length of the elements. See the example below:

# creating list of strins
mylist = ('welcome', 'to', 'golinux', 'cloud')

# python sort list based on key value
sorted_list = sorted(mylist, key=len)

# printing the list
print(sorted_list)

Output:

['to', 'cloud', 'welcome', 'golinux']

See in the example above that the list is sorted based on the length of the strings.

 

Summary

A Python list is an ordered and changeable collection of data objects. It can contain different data typed elements and repeated elements as well. In this tutorial, we learned about two different methods to sort python lists in ascending or descending order. We learned the basic syntax of the python sort() and python sorted() method. We applied these methods on various different data typed lists to sort them in ascending and descending order. We also discussed the two optional parameters that these methods take and their role in sorting the lists. To summarize, this tutorial contains all the necessary information that you need to know in order to start working with the sorting of lists in Python.

 

References

10+ examples on python sort() and sorted() function

 

Further Reading

Python lists
Python sort() method
Python sorted() method

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment