Python Built-in Methods – Python sorted() Function

Python sorted() Function

Sorts the items of an iterable

Usage

The sorted() method sorts the items of any iterable

You can optionally specify parameters for sort customization like sorting order and sorting criteria.

Syntax

sorted(iterable,key,reverse)

The method has two optional arguments, which must be specified as keyword arguments.

Parameter Condition Description
iterable Required Any iterable (list, tuple, dictionary, set etc.) to sort.
key Optional A function to specify the sorting criteria.
Default value is None.
reverse Optional Settting it to True sorts the list in reverse order.
Default value is False.

Return Value

The method returns a new sorted list from the items in iterable.

Sort Iterables

sorted() function accepts any iterable like list, tuple, dictionary, set, string etc.

# strings are sorted alphabetically
L = ['red', 'green', 'blue', 'orange']
x = sorted(L)
print(x)
# Prints ['blue', 'green', 'orange', 'red']

# numbers are sorted numerically
L = [42, 99, 1, 12]
x = sorted(L)
print(x)
# Prints [1, 12, 42, 99]

If you want to sort the list in-place, use built-in sort() method.

sort() is actually faster than sorted() as it doesn’t need to create a new list.

# Sort a tuple
L = ('cc', 'aa', 'dd', 'bb')
x = sorted(L)
print(x)
# Prints ['aa', 'bb', 'cc', 'dd']

sorted() function sorts a dictionary by keys, by default.

D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D)
print(x)
# Prints ['Bob', 'Max', 'Sam', 'Tom']

To sort a dictionary by values use the sorted() function along with the values() method.

D = {'Bob':30, 'Sam':25, 'Max':35, 'Tom':20}
x = sorted(D.values())
print(x)
# Prints [20, 25, 30, 35]

Sort in Reverse Order

You can also sort an iterable in reverse order by setting reverse to true.

L = ['cc', 'aa', 'dd', 'bb']
x = sorted(L, reverse=True)
print(x)
# Prints ['dd', 'cc', 'bb', 'aa']

Sort with Key

Use key parameter for more complex custom sorting. A key parameter specifies a function to be executed on each list item before making comparisons.

For example, with a list of strings, specifying key=len (the built-in len() function) sorts the strings by length, from shortest to longest.

L = ['orange', 'red', 'green', 'blue']
x = sorted(L, key=len)
print(x)
# Prints ['red', 'blue', 'green', 'orange']

Sort with Custom Function

You can also pass in your own custom function as the key function. A key function should take a single argument and return a key to use for sorting.

# Sort by the age of students
def myFunc(e):
  return e[1]	# return age

L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=myFunc)
print(x)
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]

Sort with lambda

A key function may also be created with the lambda expression. It allows us to in-line function definition.

# Sort by the age of students
L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=lambda student: student[1])
print(x)
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]

Sort with Operator Module Functions

To access items of an iterable, Python provides convenience functions like itemgetter() and attrgetter() from operator module.

# Sort by the age of students
from operator import itemgetter
L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=itemgetter(1))
print(x)
# Prints [('Max', 25), ('Bob', 30), ('Sam', 35)]

Multiple Level Sorting

The operator module functions allow multiple levels of sorting as well.

# Sort by grade then by age
from operator import itemgetter
L = [('Bob', 'B', 30),
	 ('Sam', 'A', 35),
     ('Max', 'B', 25),
     ('Tom', 'A', 20),
     ('Ron', 'A', 40),
     ('Ben', 'B', 15)]
x = sorted(L, key=itemgetter(1,2))
print(x)
# Prints [('Tom', 'A', 20),
#         ('Sam', 'A', 35),
#         ('Ron', 'A', 40),
#         ('Ben', 'B', 15),
#         ('Max', 'B', 25),
#         ('Bob', 'B', 30)]

Sort Custom Objects

Let’s create a list of custom objects.

# Custom class
class Student:
	def __init__(self, name, grade, age):
		self.name = name
		self.grade = grade
		self.age = age
	def __repr__(self):
		return repr((self.name, self.grade, self.age))

# a list of custom objects
L = [Student('Bob', 'B', 30),
	Student('Sam', 'A', 35),
	Student('Max', 'B', 25)]

Here are some techniques to sort a list of custom objects.

# with lambda
x = sorted(L, key=lambda student: student.age)
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# with attrgetter
from operator import attrgetter
x = sorted(L, key=attrgetter('age'))
print(x)
# [('Max', 'B', 25), ('Bob', 'B', 30), ('Sam', 'A', 35)]
# Custom Objects - Multiple Level Sorting
# Sort by grade then by age
x = sorted(L, key=attrgetter('grade', 'age'))
print(x)
# [('Sam', 'A', 35), ('Max', 'B', 25), ('Bob', 'B', 30)]

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.