Sorting Out .sort() and sorted()

Sorting Out .sort() and sorted()

Sometimes sorting a Python list can make it mysteriously disappear.  This happens even to experienced Python programmers who use .sort() when they should have used sorted() instead. The differences between these two ways of sorting a list are presented in this blog.

Author:  Eric Olsen, Senior DTX Services Consultant and Instructor, Ph.D.

 

Introduction

If you have a Python list, there are two basic ways to get it sorted. First, you can use the method built into the list object: .sort(). Second, you could use the top-level Python function sorted(). They have similar capabilities, controlled by the same keyword arguments (key and reverse). So, how do you know which one you should use in a particular place in your code?

The .sort() Method

One of the several methods built into Python list objects is .sort(). This is an in-place sort. It directly acts on the list, changing the order of items in it.

For example:

>>> l = [4, 2, 1, 3]
>>> l.sort()
>>> print(l)
[1, 2, 3, 4]

Note that the call to .sort(), like a call to any Python method or function, returns a value. In the case of .sort(), the return value is the object None.

>>> m = l.sort()
>>> print(m)
None

This can cause problems when you are trying to save your sorted list to a new variable name (as in the example above), or when you are trying to run a for loop over a sorted list:

>>> for item in l.sort():
...    print(item)
TypeError: 'NoneType' object is not iterable

It can also cause problems when trying to return a sorted list from a function:

>>> def build_list():
...    x = ['c', 'a', 'd', 'b']
...    return(x.sort())
>>> m = build_list()
>>> print(m)
None

All of these problems are the result of expecting a list’s .sort() method to return the list, rather than the None object that it actually returns. Remember that this method is used for in-place sorting only – it acts directly on the given list, replacing the current contents with new sorted contents.

The sorted() Function

In contrast, the sorted() function makes a copy of your list as it sorts it and returns that copy to you. As a result, it does two important things. First, it leaves the original list intact. Second, it hands you a sorted list object that you can store, use in a loop, or return from a function.

For example:

>>> l = [4, 2, 1, 3]
>>> m = sorted(l)
>>> print(l) # unchanged
[4, 2, 1, 3]
>>> print(m) # sorted
[1, 2, 3, 4]

In each case where .sort() went wrong above, you should use sorted() instead.

Note that sorted() can also sort objects other than lists. Anything that is iterable (e.g., tuples, dictionaries, etc.) can be sorted.

Summary

Use .sort() for in-place list sorts. This operation returns a None, making it unsuitable for saving as a new list, using in loops, returning from functions, and any other context where you need a list object to continue. This in-place behavior can yield minor speed ups for larger lists compared to the sorted() approach since a copy is not being made during execution.

Use sorted() where you want to preserve the order of the original list but need a sorted list object to do some task. This generally happens when you want to save a sorted copy of your list, when you want to run a loop in a sorted order, or when you want to return a sorted list from a function.

About the Author

Eric Olsen holds a Ph.D. in history from the University of Pennsylvania, a M.S. in software engineering from Pennsylvania State University, and a B.A. in computer science from Utah State University. Eric spent three decades working in software development in a variety of fields, including atmospheric physics research, remote sensing and GIS, retail, and banking. In each of these fields, Eric focused on building software systems to automate and standardize the many repetitive, time-consuming, and unstable processes that he encountered.

About Enthought Training

Enthought Training supports scientists and engineers as they solve the problems of today while developing the creative thinking needed to realize the possibilities of digital technologies. Attend our upcoming courses and gain the knowledge and experience to tackle challenges with scientific data. Learn more here.

 

Share this article:

Related Content

Exploring Python Objects

Introduction When we teach our foundational Python class, one of the things we do is make sure that our students know how to explore Python…

Read More

Choosing the Right Number of Clusters

Introduction When I first started my machine learning journey, K-means clustering was one of the first algorithms I was introduced to – and it is…

Read More

Prospecting for Data on the Web

Introduction At Enthought we teach a lot of scientists and engineers about using Python and the ecosystem of scientific Python packages for processing, analyzing, and…

Read More

Configuring a Neural Network Output Layer

Introduction If you have used TensorFlow before, you know how easy it is to create a simple neural network model using the Keras API. Just…

Read More

No Zero Padding with strftime()

One of the best features of Python is that it is platform independent. You can write code on Linux, Windows, and MacOS and it works…

Read More

Got Data?

Introduction So, you have data and want to get started with machine learning. You’ve heard that machine learning will help you make sense of that…

Read More

Sorting Out .sort() and sorted()

Sorting Out .sort() and sorted() Sometimes sorting a Python list can make it mysteriously disappear.  This happens even to experienced Python programmers who use .sort()…

Read More

A Beginner’s Guide to Deep Learning

Deep learning. By this point, we’ve all heard of it. It’s the magic silver bullet that can fix any complex problem. It’s the special ingredient…

Read More

Scientists Who Code

Digital skills personas for success in digital transformation The digital skills mix varies widely across companies, from those just starting to invest in digital transformation…

Read More

Giving Visibility to Renewable Energy

The ultimate project goal of EnergizAIR Infrastructure was to raise individual awareness of the contribution of renewable energy sources, and ultimately change behaviors. Now ten…

Read More

Join Our Mailing List!

Sign up below to receive email updates including the latest news, insights, and case studies from our team.