Member-only story

Advanced Sorting in Python Using Lambdas and Custom Functions

Sort lists of elements of non-basic data types (e.g., int, str)

Yong Cui
Better Programming

--

Photo by Martin Sanchez on Unsplash

Basic Sorting

When it comes to sorting, the most-used Python functions are sorted() and sort().

Although there are some differences in their usage, memory usage, and operation speed, as discussed in a previous Medium article, both functions can be used to sort a list. Below is a simple example.

In the above example, there are a few things to highlight for those who are less familiar with the sorted() and sort() functions.

  • The sort() function is actually an instance method of the list data type, such that the usage is list.sort().
  • The sorting operation by sort() is in place and returns None. Thus, if you check the type by running type(numbers.sort()), the output will be NoneType.
  • Unlike the sort() function, the sorted() function has better flexibility by allowing the argument to be a list or any other iterable

--

--

Responses (2)