How to sort a list in Python

How to sort a list in Python

In this article, we’ll learn how to sort list, list of dictionaries, and list of tuples in Python.

We can sort lists, lists of tuples, and list of dictionaries in two ways: Using built-in functions and without using built-in functions.

How to sort a list in python using built-in functions

How to sort a list using sort() method

sort() is a built-in list method, which means it can only be used with lists. In the following code snippet, we’re going to create a list object length and then we’ll sort it in ascending and descending order one by one.

#python program code to sort a list in ascending order
length = [3, 4.4, 2, 5, 5.3, 1.9, 6]
length.sort()
print(length)

Output:

[1.9, 2, 3, 4.4, 5, 5.3, 6]

Now, how to sort a list in descending order?

The simplest method of doing so is by adding the reverse flag inside the sort() method and change its value to True. Note that the default value of the reverse flag is True. The following program code does the same using the same sort() method.

#python program code to sort a list in descending order
length = [4.4, 3, 2, 5.2, 2.7, 1.5, 6]
length.sort(reverse=True)
print(length)

Output:

[6, 5.2, 4.4, 3, 2.7, 2, 1.5]

The sort() function has one more flag available, which is key. This is used to modify the sorting process based on the key. For example, if a list of string values is to be sorted based on their length, then you will have to mention that as the value of key. Look at the example code snippet below:

Problem: Sort a list of strings in python

Program 1: Sort list of strings in ascending order

#Program to sort a list of strings in python according to their length
str = ['visit', 'programming', 'articles', 'for', 'more']
str.sort(key=len)
print(str)


Program 2: Sort list of strings in descending order

str = ['learn', 'interesting', 'concepts', 'of', 'programming', 'here']
str.sort(key=len, reverse=True)
print(str)

Output:

Output #1:

['for', 'more', 'visit', 'articles', 'programming']

Output #2:

['interesting', 'programming', 'concepts', 'learn', 'here', 'of']

The above program checks for the key, which is the length of the string, and sorts the list according to the lengths of the string elements.

Also read: Python project: Create YouTube video downloader using python

How to sort a list of lists in python

This program snippet sorts the list of lists according to their first element in ascending order.

list1 = [[3,5], [6,2], [9,4], [23,7], [5,6]]
list1.sort()
print(list1)

Output:

[[3, 5], [5, 6], [6, 2], [9, 4], [23, 7]]

What if you want to sort the list according to the second elements of the lists? To do so, you will have to mention that inside the key flag. To create a value for key flag, we will define a method which returns the second element of a list passed to it.

Below is the code to sort the list of lists according to the second elements of the lists in decreasing order.

#method to create value for key flag
def sec(element):
    return element[1]

list1 = [[3,5], [6,2], [9,4], [23,7], [5,6]]
list1.sort(key=sec,reverse=True)
print(list1)

Output:

[[23, 7], [5, 6], [3, 5], [9, 4], [6, 2]]

Similarly, you can sort a list of tuples using the sort() method. Below is the example program snippet for that.

How to sort a list of tuples in Python

list = [(2,3), (3,1), (6,2), (4,5), (9,8)]
list.sort()
print(list)

Output:

[(2, 3), (3, 1), (4, 5), (6, 2), (9, 8)]

Now, what if you want to sort a list of dictionaries in Python? Continue reading for easy understanding.

How to sort a list of dictionaries in Python?

Sorting a dictionary in python is a bit complex as you might already have tried using the sort() method. We get an error while trying to sort the list of dictionaries using the sort() method because dictionaries are unorderable types, therefore we cannot compare two dictionaries.

So what are we supposed to add or remove to do that? The answer is simple. We will have to provide some value to the key flag, according to which it will be able to sort the dictionaries inside the list.

We will import itemgetter from operator module to get the particular item/key from the dictionary. Learn more about it from the official website of python.

The following program snippet implements the idea that we just discussed.

from operator import itemgetter
data =[{ "name": "Tom", "age": 40, "doj": '1992-05-12' }, { "name": "Mark", "age": 35,"doj": '1995-10-23'}, { "name": "Parker", "age": 47, "doj": '1992-09-17'}, { "name": "John", "age": 32, "doj": '1999-03-30' }]
data.sort(key=itemgetter('name'))
print(f'User data arranged according to their name:\n{data}')
data.sort(key=itemgetter('doj'))
print(f'\nUser data arranged according to the joining date:\n{data}')

Output:

User data arranged according to their name:
[{'name': 'John', 'age': 32, 'doj': '1999-03-30'}, {'name': 'Mark', 'age': 35, 'doj': '1995-10-23'}, {'name': 'Parker', 'age': 47, 'doj': '1992-09-17'}, {'name': 'Tom', 'age': 40, 'doj': '1992-05-12'}]

User data arranged according to the joining date:
[{'name': 'Tom', 'age': 40, 'doj': '1992-05-12'}, {'name': 'Parker', 'age': 47, 'doj': '1992-09-17'}, {'name': 'Mark', 'age': 35, 'doj': '1995-10-23'}, {'name': 'John', 'age': 32, 'doj': '1999-03-30'}]

Now, let’s learn how to sort a list in python without using sort().

How to sort a list in python without sort function

A list in python can be sorted using the for loop. The following program snippet uses for loop to sort a list of numbers.

#Sort a list in python using for loop
num = [9, 2, 5, 1, 7, 3, 4, 8, 22, 93, 6]

#use for loop instead of sort method here
for i in range(0, len(num)):
    for j in range(i+1,len(num)):
        if(num[i]>num[j]):
            num[i],num[j] = num[j],num[i]   #swapping trick in python
print(num)

Output:

Now you must be wondering how to sort the list in descending order without using sort function. Actually it is very simple, just invert the condition inside the if statement. Learn from the code snippet below.

num = [9, 2, 5, 1, 7, 3, 4, 8, 22, 93, 6]

for i in range(0, len(num)):
    for j in range(i+1,len(num)):
        if(num[i]<num[j]):      #condition reversed
            num[i],num[j] = num[j],num[i]  
print(num)

Output:

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

This is all for now, if you need more program examples, let me know in the comments.

In this article, we learned how to sort a list in python using built-in functions and using for loop. Then we went for writing program snippets to sort a list of strings, lists, and dictionaries using the sort method.

If you learned something from this article, share this with your programmer friends or community.

Happy coding!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →

Leave a Reply

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