How to Sort in Python – [Strings, Numbers, List of Lists, Tuples]

Sorting data is just one of the things you can do with Python. It is the bread and butter of programming.

If you’ve worked with data as a programmer or a simple user, you had to sort that data at some point.

Sorting data, from the coder’s point of view, can get tricky depending on the type and amount of data you have to work with but, if you’re serious about programming, it’s one of the things you’ll have to master.

Sort vs Sorted in Python

There may be very similar in appearance, especially if you look at the end result, but there are many differences between the sort() method and sorted() function.

The most obvious difference is the one I’ve pointed out earlier:

  • sort() is a method that can be applied to a list to sort its data
  • sorted() is a function that takes a list as a parameter and returns a new sorted list of the items of the original list.

The difference may not seem relevant at first glance but have a huge impact while handling data, as the code below will demonstrate:


## using the sort method and sorting function
lst1 = [3, 1, 5]
lst2 = [6, 2, 4]
# show data unsorted
print(lst1, lst2)
lst1.sort()
srt = sorted(lst2)
# show data again
print(lst1, lst2)
print(srt)

I have declared and defined two lists called lst1 and lst2and showed the content of the lists in the console using the print() function.

I’ve sorted lst1 using the sort() method and sorted lst2 using the sorted() function.

After using print() to show the data again, you can see how lst1 has been sorted while lst2 remains unchanged.

This happens because the function sorted() doesn’t alter lst2 in any way. It just sorts a copy of it, which it returns as a parameter and we’ve saved the result in the variable srt.

So, to print the sorted list lst2 to console you need to print the list called srt as shown in the output console below:


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

As the console shows;

  • in the first line, we can see the unsorted values inside lists lst1 and lst2.
  • in the second line, lst1 has been sorted while lst2 remains the same,
  • and the last line contains list srt, which now holds the sorted values from lst2.

How to Reverse The Order Of A List In Python?

Now that we’ve seen the difference between the sort() method and the sorted() function, it’s essential to talk about one parameter we encounter in both, called reverse.

The reverse parameter is of a Boolean type, which means it can only accept true or false values.

  • If the reverse parameter is set to true, the sort() method or sorted() function will sort the list in descending order
  • and if set to false the list will be sorted ascending
  • By default, the reverse parameter is set to false, that’s why I haven’t specified anything in the code I’ve presented to you earlier.

Next, I’ll present how the reverse parameter can be used in both cases with the help of another script:


## using the reverse parameter
lst1 = [3, 1, 5]
lst2 = [6, 2, 4]
# sort data
lst1.sort()
srt = sorted(lst2)
# show result in the console
print(lst1, srt)
# sort data with the reverse parameter active
lst1.sort(reverse=True)
# show result
print(lst1, sorted(lst2, reverse=True))

The example above uses the same lists used in the earlier example, sorts them, and then sorts them with the reverse parameter set to true.

The first print() function shows the lists sorted ascending, while the two lists are sorted in descending order with the reverse parameter set to true.

The code above will return the following output:


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

How to Sort Numbers in Python

Sortingnumeric values in Python is pretty straight-forward. The procedure is identical if we have to work with a list containing float type variables (1.05, 2.1, 20.9), integer (1, 2, 3), or even a list containing both float and integer type variables.

How to Sort A List of Strings in Python

We have covered the basics of sorting numeric data with Python in the previous two chapters, so let us proceed with sorting a list of strings.

Now that you’re more accustomed to collection data types (the lists I was talking about earlier), I should clarify that there are many collections (which are similar to arrays but not the same) available in Python.

Below you’ll see all collections and, between the brackets, the description:

  • List (an ordered and changeable collection);
  • Tuple (ordered and immutable);
  • Set (unordered and unindexed);
  • Dictionary (unordered and indexed).

Sorting a list of strings is the same as sorting a list of integer values, which, as I’ve said before, is similar to how you would sort an array.

As always, the fastest way to understand how a list of strings works is to create one so let’s get cracking:


## sorting a list of characters
clist = ['b', "ch", 'def', "z"]
clist.sort() # sorting data
# showing sorted data in the console
print(clist)
rlist = sorted(clist, reverse=True) # sorting data reversed
# show in the console
print(rlist)

Three distinct things can be observed from the code above:

  1. Unlike the C programming language, it doesn’t matter in Python if you enclose characters and strings of characters in single or double quotation marks;
  2. Lists containing strings will automatically be sorted alphabetically while lists containing numbers will be sorted numerically without any intervention from the programmer;
  3. The sort() method and the sorted() function are used to sort strings in the same way you use them while sorting numeric values.

If compiled, the script above will give the following result:


['b', 'ch', 'def', 'z']
['z', 'def', 'ch', 'b']

Now, let’s dig a bit deeper into string sorting.

Case Insensitive Sorting

One thing you may not notice, at first, is that the sorting of strings in Python is also case sensitive, as the code below will show:


## sorting a list of characters -- case-sensitive
clst = ['b', 'A', 'c', 'B', 'D', 'd', 'a', 'C']
clst.sort() # sorting data
# showing in console
print(clst)
clst.sort(reverse=True) # sorting data reversed
# show in the console
print(clst)

The code presented earlier will have the following output:


['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
['d', 'c', 'b', 'a', 'D', 'C', 'B', 'A']

Uppercase variables are sorted and then lowercase variables. At the same time, for the reverse, it’s the other way around. Clearly, the sort() method and sorted() function are case-sensitive.

If you don’t want that, and want instead case insensitive sorting you have to specify it in the key argument of the sorted() function or sort() method.

The key argument allows you to add a custom function that will be executed to create a custom order of the list’s elements.

As always in programming, the clearest way to demonstrate a concept is to start coding, so let’s observe the example below:


## sorting a list of characters -- case-insensitive
ciLst = ['b', 'A', 'c', 'B', 'D', 'd', 'a', 'C']
siLst = sorted(ciLst, key=str.casefold) # sorting the data
# showing result in the console
print(siLst)

As can be seen from the coding example given earlier, we have added the str.casefold method to the key parameter.

The casefold method is part of the str namespace and was designed for situations just like the one we’re facing or, more specifically, to sort lists while ignoring whether the letter’s uppercase or lowercase.


['A', 'a', 'b', 'B', 'c', 'C', 'D', 'd']

Please note that the str.casefold method is only available for Python 3.3 and newer versions, but there are ways to obtain a case insensitive sorting in earlier versions of Python.

How to Sort the Letters In A String Alphabetically

Moving forward, one question that often pops up in blogs around the world is the best way to alphabetically sort a list of non-English letters (or special characters). Now, the world of Unicode may seem very vast and daunting at first.

Still, there are many frameworks and libraries out there that can make that work a lot easier, especially in the Python programming environment.

One library that can make life a lot easier when working with Unicode characters in Python is PyICU.

One lesser-known fact is that, in a lot of programming languages, strings can be easily converted into a list of characters (some programming languages interpret strings as a list of characters, but that’s another story).

It is important to be able to convert easily and handle data regardless of the type if you want to be an accomplished programmer, so let move forward.

The following example will show how to sort the by the first letter of each word in a string alphabetically:


## converting and sorting a string
# class to convert string to a list
def StrToLst(string):
    lst = list(string.split(" "))
    return lst

str1 = "Sorting strings in Python"
lst1 = StrToLst(str1) # converting string to list
lst1.sort(key=str.casefold) # sorting the list
print(lst1) # showing the list's content in console

As you can see, we have a string called str1 that needs to be converted to a list and then sorted alphabetically. To accomplish that, I’ve created a custom function called StrToLst (so String To List, basically), which separates each element in the string by a given character (space in our case) using the split method. That being done, we case-insensitive sort the list, like we did while sorting characters and show the result onto the console:


['in', 'Python', 'Sorting', 'strings']

The console will now proudly show our string sorted alphabetically and case-insensitively as well.

Sorting A List of Objects

This is something you don’t hear about every day, and some people frown upon it, but objects can be stored into lists or arrays in many programming languages, and Python is one of them.

You may have noticed in the previous example that I’ve created a function called StrToLst. Some may say that’s a procedure, yet I’ve called it a function because Python is an object-oriented programming language.

In the following example, we’ll create a class having a constructor, add some objects created from that class to a list and then sort that list based on parameters of the class, as mentioned earlier. It’s a lot simpler than it may sound, so let’s get cracking:


## sorting a list of objects
# class to hold data of different people
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# create an empty list
olst = []

# add data to the list
olst.append( People('Frank', 35) )
olst.append( People('Sam', 20) )
olst.append( People('Jackie', 27) )
olst.append( People('Audrey', 30) )

# show data
for obj in olst:
    print(obj.name, obj.age)

In the example above, we have created a class called People, which can hold basic information like the name and age of a certain individual.

We create an empty list called olst and add a few objects to it using the append method. Next, we proceed to display that data in the console.

You may notice that we don’t display the data like in previous examples. Just adding the olst variable in the print function as we did before will only display the memory address of each object, which is not too helpful for the average user.

Because of that, we use a forloop to cycle through each element from the list and retrieve its name and age.

Moving on, I’ve also mentioned we’ll sort the list. The next lines of code will show how to sort a list of objects:


# sort the list
olst.sort(key=lambda o: o.age)

print() # add a line break

# show data
for obj in olst:
    print(obj.name, obj.age)

In the code above, we can see how in the key parameter of the sort() method, I’ve added a lambda function that will enable us to sort the list by the age parameter of the objects. We then proceed to show the sorted list as seen in the console below:


Frank 35
Sam 20
Jackie 27
Audrey 30

Sam 20
Jackie 27
Audrey 30
Frank 35

In the console, we can see the unsorted list from line 1 to line 4, the same elements sorted by age from line 6 to line 9.

The elephant in the room here is the lambda function. To understand the code above, you must first understand what a lambda function is.

The lambda function is another interesting feature that Python offers to programmers. It is a custom function that can be used in arguments or even as a return value and is very useful to automate calculations or, like I’ve used before, to cycle through elements.

The lambda function feature is a neat way to embed functional programming in an otherwise object-oriented programming environment like Python.

How to Sort a List of Lists in Python

Another feature that may be useful is to sort a list containing lists. Yes, you’ve read this right, and it’s not a typo either.

There are cases in which you need to add lists of elements in a list. Sorting those lists would be a real hassle if not for some neat features offered by Python.

Let’s see an example:


## sorting a list of lists
# import the itemgetter function
from operator import itemgetter

# the list
lst2 = [ [1,3,5], [0,0,0], [10,20,30], [2,4,6] ]

# sort it using the itemgetter
lst2.sort(key=itemgetter(1))

print(lst2) # show data

In the code above, you can notice that we import the itemgetter function from the operator module. In the example above, the itemgetter function is the most efficient, but the same result can be achieved using a lambda function.

We use the itemgetter function to sort the list by the first element, as can be seen below in the console.


[[0, 0, 0], [1, 3, 5], [2, 4, 6], [10, 20, 30]]

You may be wondering why [0,0,0] is considered to be the first element in the list when clearly it is the second. The reason behind that is that in lists and arrays, the first element is located on position 0 while the second on position 1 and so forth. The itemgetter function sorts the list by the element in position 1, as can be seen in the output.

The itemgetter function has a vital role in this example, so an explanation of its function and usage is in order.

I think the Python’s documentation gives the best answer to the role and usage of the itemgetter function: “Returns a callable object that fetchesitemfrom its operand using the operand’s__getitem__()method. If multiple items are specified, returns a tuple of lookup values“. [1]

How to Sort List Of Tuples in Python

As I’ve said before, you can store other data structures into lists, including other lists, tuples, dictionaries, and so on.

I’ve mentioned before what tuples are: ordered and immutable structures so they cannot be sorted, but you can sort a list containing tuples by a given tuple.

The code of this example will look eerily similar to the code I’ve given on the previous chapter (Sorting a list of lists), so I’ll just show you how to create the list of tuples:


# the list of tuples
lst2 = [ (1,3,5), (0,0,0), (10,20,30), (2,4,6) ]

And we’ll sort the list by the second element, so even the itemgetterfunction remains unchanged.

You can observe in the code above the only difference between lists and tuples (in our case) are the round brackets as opposed to the square brackets used in the previous example. After compiling the code, we’ll get the following result:


[(0, 0, 0), (1, 3, 5), (2, 4, 6), (10, 20, 30)]

As before, the only apparent differences are the round brackets.

How to Sort a Dictionary by Value Or Key in Python

Dictionaries are unordered, changeable, and indexed collections of data. They cannot be sorted, but a sorted representation of the dictionary can be retrieved using the sorted() function.

And because of their nature sorbing dictionaries is different from sorting a list and is, in fact, similar to sorting a class. The example below will give you an idea on how to sort a dictionary:


# sorting a dictionary
# create a dictionary
dict1 = { 'D':4, 'A':1, 'C':5, 'B':2 }

# show data
for x,y in dict1.items():
    print(x,y)

# sort by key
sk1 = sorted(dict1.keys(), key=lambda d: d[0])

# show data sorted by key
print('---')
for x in sk1:
    print(x)

# sort by value
sv1 = sorted(dict1.values())

# show data sorted by key
print('---')
for x in sv1:
    print(x)

As you can see, the code is pretty straight-forward and self-explanatory. We use methods available for dictionaries and get the keys, then the values, and sort the dictionary accordingly.

The following output will be produced:


D 4
A 1
C 5
B 2
---
A
B
C
D
---
1
2
4
5

One essential note: if you have experience programming with C or C++, you probably compared lists with arrays. That’s a legit comparison, but dictionaries shouldn’t be compared with arrays as they are, and behave differently. They are, in fact, more similar to data structures (struct).

Understanding Custom Sort in Python (Using A Comparator Function)

Python has many default methods for sorting lists and other data structures, but every now and then, you’ll find they are not enough, and you need to create your own custom sort.

The most obvious way of doing this is to use a custom function in the key parameter of the sort() method or sorted() function. This is exactly what the code below will explain:


## custom sort | using a comparator function
# compare two values and return the biggest one
def compare(x, y):
    if x>y:
        return x
    elif x==y:
        return 0
    else:
        return y

# create a list
lst = [ 1, 5, 10, 3, 8, 4 ,15 ]

print(lst) # show data

slst = sorted(lst, key=lambda x: compare(x, x+1)) # sort list

As you can see from the code above, I’ve created a custom compare function that returns the biggest occurrence out of two values. I’ve used that custom function as a comparator using the key parameter in the sorted() function. With the help of a lambda function, I’ve iterated through all elements inside the list.As you can see in the console output below, the list has been sorted correctly:


[1, 5, 10, 3, 8, 4, 15]
[1, 3, 4, 5, 8, 10, 15]

That covers the basics of sorting with a custom comparator function. Hope you enjoyed it.

Pin this article to your Pinterest Python board

Sorting Techniques in Python