libri-javascript-python

In this lesson I will talk about Python list sort method which is useful for quickly sorting a list in ascending or descending order.

So let’s create some examples to understand how it works.

Ascending / descending sorting of a list with Python list sort

I take as input a list of any numbers and apply the sort method on it to sort in ascending direction.


numbers = [1,7,9,3,4]
numbers.sort()
print(numbers)

Python list sort reverse parameter

We now sort in descending order using the optional reverse parameter. If reverse is False, the list is sorted in ascending order, it is in fact the default value, if reverse is True, the list is sorted in descending order.

Here is an example:


numbers = [1,7,9,3,4]
numbers.sort(reverse=True)
print(numbers)

Key parameter

The key parameter allows you to specify a sort order based on a function.

Let’s take an example by sorting a list based on the length of the names. We define a function that calculates the length of the names of an array.

We apply the sorting by setting the key with the defined function.

Here is the simple example of the Python list sort () algorithm:


names = ['Paul','Robert','Elena','Tom']

def len_names(array):
   return len(array)

names.sort(key=len_names)

print(names)

If we want to order in reverse order, just indicate the reverse parameter as well.


names = ['Paul','Robert','Elena','Tom']

def len_names(array):
   return len(array)

names.sort(reverse = True, key=len_names)

print(names)

Sorting example with Python list sort

In this example we try to sort a list of uppercase and lowercase letters.

This is an example:



names = ['B','a','C','s']
names.sort()

print(names)

In output we will have: [‘B’, ‘C’, ‘a’, ‘s’].

The result is not what we expected! Because? Obviously because each letter of the alphabet corresponds to a character of the ASCII encoding and the uppercase letters have a different encoding than the lowercase ones.

We can obtain a correct ordering for example by converting all the characters in the list to lowercase.


names = ['B','a','C','s']
names_order = [name.lower() for name in names]
names_order.sort()

print(names_order)

We could also write like this:


names = ['B','a','C','s']

for i in range(len(names)):
    names[i] = names[i].lower()

names.sort()

print(names)

Conclusion

In this lesson we have seen how to quickly sort a list using Python sort, in the next lessons we will study some sorting algorithms for educational purposes.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot