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

Leveraging AI for More Efficient Research in BioPharma

In the rapidly-evolving landscape of drug discovery and development, traditional approaches to R&D in biopharma are no longer sufficient. Artificial intelligence (AI) continues to be a...

Read More

Utilizing LLMs Today in Industrial Materials and Chemical R&D

Leveraging large language models (LLMs) in materials science and chemical R&D isn't just a speculative venture for some AI future. There are two primary use...

Read More

Top 10 AI Concepts Every Scientific R&D Leader Should Know

R&D leaders and scientists need a working understanding of key AI concepts so they can more effectively develop future-forward data strategies and lead the charge...

Read More

Why A Data Fabric is Essential for Modern R&D

Scattered and siloed data is one of the top challenges slowing down scientific discovery and innovation today. What every R&D organization needs is a data...

Read More

Jupyter AI Magics Are Not ✨Magic✨

It doesn’t take ✨magic✨ to integrate ChatGPT into your Jupyter workflow. Integrating ChatGPT into your Jupyter workflow doesn’t have to be magic. New tools are…

Read More

Top 5 Takeaways from the American Chemical Society (ACS) 2023 Fall Meeting: R&D Data, Generative AI and More

By Mike Heiber, Ph.D., Materials Informatics Manager Enthought, Materials Science Solutions The American Chemical Society (ACS) is a premier scientific organization with members all over…

Read More

Real Scientists Make Their Own Tools

There’s a long history of scientists who built new tools to enable their discoveries. Tycho Brahe built a quadrant that allowed him to observe the…

Read More

How IT Contributes to Successful Science

With the increasing importance of AI and machine learning in science and engineering, it is critical that the leadership of R&D and IT groups at...

Read More

From Data to Discovery: Exploring the Potential of Generative Models in Materials Informatics Solutions

Generative models can be used in many more areas than just language generation, with one particularly promising area: molecule generation for chemical product development.

Read More

7 Pro-Tips for Scientists: Using LLMs to Write Code

Scientists gain superpowers when they learn to program. Programming makes answering whole classes of questions easy and new classes of questions become possible to answer….

Read More