Python Beginner’s Guide to Sort Python List – Python Tutorial

By | August 13, 2019

Python list is a common used data type in python, in this tutorial, we will introduce you how to sort a list. You can learn how to sort by following our tutorial.

python sort list tutorials and examples

Firstly, we can use list.sort() function to sort a python list.

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

Where:

reverse – If true, the sorted list is reversed (or sorted in Descending order)
key – function that serves as a key for the sort comparison

Create a python list

list = [3, 4, 5, 6, 2, 6]

Sort from small to big

list.sort()
print(list)

The result is:

[2, 3, 4, 5, 6, 6]

Sort from big to small

list.sort(reverse=True)
print(list)

The result is:

[6, 6, 5, 4, 3, 2]

Then the elements in python list is composed type, such as tuple or dictionary, how to sort?

Create a list to contains some tuples

list=[('tom', 23), ('lily', 32), ('andrew', 12), ('kate', 21)]

Sort by person name

list.sort()
print(list)

List will sort by the first key of each tuple defautly, so we can get result like:

[('andrew', 12), ('kate', 21), ('lily', 32), ('tom', 23)]

Sort by person age

list.sort(key = lambda x: x[1] , reverse=True)
print(list)

We should tell list.sort() function sort elements by sencond key in each tuple, so we can get result like:

[('lily', 32), ('tom', 23), ('kate', 21), ('andrew', 12)]

Leave a Reply

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