Python Sort List

Filed Under: Python

In this tutorial, we are going to learn about Python Sort List. In the previous tutorial we learned about Python Namespace.

Python Sort List

I assume that you are familiar with Python List. If you don’t know about Python List, you can learn it from here. Now we will learn about sort list in python program. But first of all, we need to know why should we sort a list.

Well, sorting is important in many aspect. Suppose you are going to donate some money. You know the financial condition of other people. Assume that you indexed their financial condition in scale between 0 to 10. So, from that list you want to donate to the person whose index is least. So, you need to sort the list in ascending order on basis of their financial condition. See the example.


people_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print('Before sorting:')
print(people_list)

people_list.sort()

print('After sorting:')
print(people_list)

The output will be


Before sorting:
[3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting:
[1.0, 2.2, 3.4, 3.8, 4.1, 5.1]

Python Sort List in Descending Order

In our previous example, we see how to sort a Python list in ascending order. Now, if we want to sort the list in descending Order, what should we do? Well, this is so simple. You have to pass a key-value pair argument in that function. If you don’t know much about Python Function and Arguments, we suggest you to read this article. However, the following code will sort python list in descending order.


people_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print('Before sorting:')
print(people_list)

people_list.sort(reverse=True)

print('After sorting:')
print(people_list)

The output will be


Before sorting:
[3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting:
[5.1, 4.1, 3.8, 3.4, 2.2, 1.0]

Python Sort List of List

You may need to sort list of list. That means, the items of the list is also a list. So, if you write the following code, it will pick the first item of the list item for comparing.


numbers = [[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]

print('Before sorting:')
print(numbers)

numbers.sort()

print('After sorting:')
print(numbers)

So, you will find the output that, the item of the list ‘number’ is sorted on basis of their first item, like below.


Before sorting:
[[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]
After sorting:
[[1, 2], [2, 1], [3, 3], [4, 3], [5, 2]]

However, you may need to sort that kind of list not basis on the first element of the child list only. Suppose, you have a list about information of few people. Each Item of the list contains a list of information about those people such as, name, age, gender. You want to sort the list of people on basis of their age. So the following code will help you to do so.


def custom_key(people):
    return people[1]  # second parameter denotes the age

numbers = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]

print('Before sorting:')
print(numbers)

numbers.sort(key=custom_key)

print('After sorting:')
print(numbers)

Here, you can see that we use the key argument to specify the element on basis of what we can sort our list. custom_key function returns the key by which our list will be sorted. So, you will see the output as


Before sorting:
[['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]
After sorting:
[['Alexa', 22, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alice', 26, 'F']]

Python Sorting Using Custom Logic

We can also implement your own logic to sort the list. That means, we can set your own rules to sort the number.

In the preceding example, we used the age as the key element to sort our list. But there goes a saying, “Ladies first!”. So want to sort our list in such way so that the female gender gets priority over male and if the gender of two person matches, the younger one gets the higher priority.

So, we have to use key argument in our sort function. But our own designed compare function needs to be converted into a key. So, we need to import a library called ‘functools’. We will use the function cmp_to_key() to convert our compare function into a key. The following example will illustrate you the custom sort of list.


import functools

def compare_function(peopleA, peopleB):
    if peopleA[2] == peopleB[2]:  # if their gender become same
        return peopleA[1] - peopleB[1]  # return true if peopleA is younger
    else:  # if their gender not matched
        if peopleB[2] == 'F':  # give peopleB first priority if she is female
            return 1
        else:  # otherwise give peopleA first priority
            return -1

numbers = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]

print('Before sorting:')
print(numbers)

numbers.sort(key=functools.cmp_to_key(compare_function))

print('After sorting:')
print(numbers)

So the output of the code will be

Python sort list, python list custom sorting

Thus, we can sort a list accordingly. That’s all about Python sort list examples. Hope that you understand the topic well. But if you have any query, feel free to ask that in comment section.

References: Official API Documentation

Comments

  1. DEANMAUER says:

    Thanks for sharing. More helpful for completing assignment and gained more stuffs. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages