Python lists are ordered collection of objects. Thus lists are capable of storing sequential or ordered data and it may happen that you require to sort this data as per your need. Python has a list function to sort its elements – the sort()
function. There are other ways as well. In this tutorial, we’ll look at how to sort a list in python.
Before we proceed, here’s a quick refresher on python lists – Lists are used to store an ordered collection of items. These items can be any type of object from numbers to strings or even another list. This makes lists are one of the most versatile data structures in python to store a collection of objects. For more, check out our guide on lists and other data structures in python.
How to sort elements of a python list?
There are a couple of ways of sorting a list in python. You can use the list function sort()
which sorts the list in-place. Alternatively, you can sort a list using the built-in sorted()
function which returns a sorted list and also works on other iterables as well.
1. Using the list function – sort()
sort()
is a list method that sorts a list in-place, meaning, the original list gets modified. By default, it sorts the list in ascending order.
Syntax:
sample_list.sort(reverse=False, key=None)
Here, sample_list is the list to be sorted. By default, the reverse
parameter is set to False
, that is, it sorts the list in ascending order. Also, the key
parameter is set to None
, meaning it does not use any custom sorting criteria by default.
Parameters:
- reverse (optional): Whether to sort the list in descending order or not. Defaults to
False
. Set it toTrue
to sort the list in descending order. - key (optional): A function to specify the sorting criteria. This function is used to get a comparison key for each list element before sorting. Defaults to
None
, that is, no function is applied on the list elements and the list gets sorted without calculating a separate key.
Returns:
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
It sorts the list in-place and does not return any value (it returns None)
Example 1: Sorting a list with default parameters.
# sort a list ls = [2, 4, 1, 3] print("Before sorting:", ls) # sort the list in ascending order ls.sort() print("After sorting: ", ls)
Output:
Before sorting: [2, 4, 1, 3] After sorting: [1, 2, 3, 4]
In the above example, the list ls
is sorted using the list function sort()
with its default parameters which sort the list in ascending order.
Example 2: Sorting a list in descending order
# sort a list ls = [2, 4, 1, 3] print("Before sorting:", ls) # sort the list in ascending order ls.sort(reverse=True) print("After sorting: ", ls)
Output
Before sorting: [2, 4, 1, 3] After sorting: [4, 3, 2, 1]
In the above example, the list ls
is sorted in descending order by passing the argument reverse=True
in the sort function.
Example 3: Sorting a list with a custom key
# sort with a specific criteria ls = [('a', 30), ('c', 20), ('b', 10)] print("Before sorting:", ls) # sort without any key ls.sort() print("After default sorting:", ls) # custom function for sorting key def get_second(tup): return tup[1] # sort with the get_second function as key ls.sort(key=get_second) print("After custom sorting:", ls)
Output:
Before sorting: [('a', 30), ('c', 20), ('b', 10)] After default sorting: [('a', 30), ('b', 10), ('c', 20)] After custom sorting: [('b', 10), ('c', 20), ('a', 30)]
In the above example, a list of tuples is sorted. First, using the default parameters which sorts the list based on the value of first element of each tuple. Then, a custom function get_second()
is used as a key to sort the list based on the value of the 2nd element of each tuple.
2. Using the function – sorted()
You can also sort a python list using the function sorted()
. It is not a list function. It’s a built-in python function that can be used used to perform a sorting operation on any iterable (example, list, tuple, string, etc). It takes the iterable as an argument and returns a sorted list.
Syntax:
sorted(iterable, reverse=False, key=None)
Parameters:
- iterable: The iterable to be sorted.
- reverse (optional): Whether to sort the list in descending order or not. Defaults to
False
. Set it toTrue
to sort the list in descending order. - key (optional): A function to specify the sorting criteria. This function is used to get a comparison key for each list element before sorting. Defaults to
None
, that is, no function is applied on the list elements and the list gets sorted without calculating a separate key.
Returns:
It returns a new sorted list from the items of the iterable.
The sorted()
function is a preferred choice when a sorted list as a return value is required. Also, it can be applied to any iterable and not just lists.
Example 1: Sorting a list
# sort a list ls = [2, 4, 1, 3] print("Original list:", ls) # sort the list in ascending order ls_sorted = sorted(ls) print("Sorted list:", ls_sorted)
Output:
Original list: [2, 4, 1, 3] Sorted list: [1, 2, 3, 4]
In the above example, the sorted()
function returns a new sorted list which is saved in the variable ls_sorted
Example 2: Sorting other iterables
# sorting a tuple tup = (2, 5, 1, 3) print("Original tuple:", tup) tup_sorted = sorted(tup) print("Sorted on tuple:", tup_sorted) # sorting a string s = "bat" print("Original string:", s) s_sorted = sorted(s) print("Sorted on string:", s_sorted)
Output:
Original tuple: (2, 5, 1, 3) Sorted on tuple: [1, 2, 3, 5] Original string: bat Sorted on string: ['a', 'b', 't']
In the above example, the sorted()
function is applied on a tuple and a string. Since both are iterables, it sorts the elements and returns a list with sorted elements.
For more on sorting in python, refer to the python docs.
Tutorials on python lists:
- Python – Check if an element is in a list
- Python – Iterate over multiple lists in parallel using zip()
- Python – Flatten a list of lists to a single list
- Pandas DataFrame to a List in Python
- Python – Convert List to a String
- Convert Numpy array to a List – With Examples
- Python List Comprehension – With Examples
- Python List Index – With Examples
- Python List Count Item Frequency
- Python List Length
- Python Sort a list – With Examples
- Python Reverse a List – With Examples
- Python Remove Duplicates from a List
- Python list append, extend and insert functions.
- Python list remove, pop and clear functions.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.