Python sorting a list banner

Python List Sort – With Examples

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.

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.

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 to True 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:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 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.

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 to True 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.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top