Sorting Data Structures in Python

Irtiza Hafiz
Level Up Coding
Published in
5 min readNov 23, 2020

--

Photo by Luke Chesser on Unsplash

Python gives you some very handy functions that you can use to sort efficiently. You can even chain sorts so that for the same data, you have a primary sort and then a secondary sort within that.

So, without further ado, let’s get started.

Sorting Fundamentals

The two primary ways you can sort in Python are:

  • sort method that comes with lists
  • sorted function which takes in any iterable

Both will sort your data in ascending order by default. But there is a crucial difference between these two approaches:

  • sort performs the sorting operation in-place. So you end up replacing your original list.
  • sorted performs the sorting operation out-of-place. That means, it returns a new list that has your sorted data and leaves the original list untouched. This way, you can use both if you need to.

The only place you want to use sort over sorted is when you have a huge list and you know you won't need the unsorted version of it. That's because, by doing the sorting in place, sort avoids the memory overhead of creating an entirely new list.

It can only have performance implications if your lists are seriously huge! Otherwise, always use sorted as it’s more functional and deterministic. You are less likely to run into bugs if you are not mutating existing data structures.

List of Numbers or Strings

At first, we are going to look at the most basic case, which is going to be a list of numbers or strings.

data_of_numbers = [50, 30, 20, 80, 10]
data_of_strings = ['d', 'a', 'c', 'b']
data_of_numbers.sort()
sorted_numbers = sorted(data_of_numbers)
# Output:
# [10, 20, 30, 50, 80]
# ['a', 'b', 'c', 'd']

By default, Python sorts your data in ascending order. If you want descending order, you can just pass in a reverseargument:

sorted_numbers = sorted(data_of_numbers, reverse=True)
sorted_strings = sorted(data_of_strings, reverse=True)

List of Tuples or Dictionaries

--

--