TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Sorted() Function
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Sorted() Function

Last updated: Oct 07, 2023 9:35 pm
By Meenakshi Agarwal
Share
12 Min Read
Python sorted function with examples
Python sorted function with examples
SHARE

Python sorted function is a built-in method. As the name suggests, it provides the functionality to sort the objects of different data types. In this tutorial, We’ll demonstrate its usage to sort a string, list, tuple, and dictionary with examples.

Contents
Sorted function syntaxPython sorted function exampleUsing sorted function on basic data typesUsing sorted() to sort listsSort tuples using sorted()Sort a dictionarySort in reverse directionSort using keySorted() function on mixed data typesSorted() vs. list sort()How to sort a user-defined type?

Sorting is a time-critical operation for any application. It can directly affect performance and speed. You may like to use it in various scenarios such as ordering a user’s activity logs by timestamp or putting a list of customers in alphabetical order. Python’s sorting function enables basic sorting, but you can also change it as per the need.

Python Sorted Function Explained

This tutorial explains everything about the sorted function such as how to use it on different types, changing the sort order, and its comparison with the python’s sort list method.

The sorted() function takes a sequence (an iterable) as input and sorts its elements in the default ascending order. The return value is the original list with all its items intact but in the sorted order.

We can sort the iterable in a particular order, i.e., either ascending or descending. It sorts the strings alphabetically while the numbers get sorted in numerical order.

It is not possible to sort a sequence that includes mixed values such as strings and numbers.

Python sorted() function uses Timsort algorithm and has O(n log n) time complexity.

Sorted function syntax

Python sorted function declaration is as follows:

sorted(iterable[, key = None][, reverse = False])

It allows three arguments from which “iterable” is mandatory and the rest two are optional. See more info on each of these below.

Iterable (Mandatory): It is the sequence you wish to sort. If you don’t specify any key, then sorting happens in the default order.

Key (Optional): It represents a function used for comparing the list elements during the sort operation.

Reverse (Optional): Another optional boolean argument, if you pass it as True, then sorting will happen in the reverse order.

Python sorted() function modifies the input list, sorts, and returns the updated list as an iterable.

Python sorted function example

Let’s sort an unordered list of alphabets using the sorted function.

sample_list = ("h", "d", "c", "a", "b", "e", "f", "g")
out_list = sorted(sample_list)
print(out_list)

Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Using sorted function on basic data types

We can apply the sorted function to different types of iterables such as strings, lists, tuples, and dictionaries.

Hence, we can use the Python sorted function on it. See the example below.

sample_str = ("Machine Learning")
out_str = sorted(sample_str)
print("Sorted output: ", out_str)
print("Ascii value of ' ': ", ord(' '))
print("Ascii value of 'L': ", ord('L'))
print("Ascii value of 'M': ", ord('M'))
print("Ascii value of 'a': ", ord('a'))

Output:

Sorted output: [' ', 'L', 'M', 'a', 'a', 'c', 'e', 'e', 'g', 'h', 'i', 'i', 'n', 'n', 'n', 'r']
Ascii value of ' ': 32
Ascii value of 'L': 76
Ascii value of 'M': 77
Ascii value of 'a': 97

After printing the sorted function output, we displayed the ASCII values of a few of the letters in the input string. It is to show that sorting is happening based on the ASCII values of the individual character.

The following Python string tutorial will help you understand more about this topic.

Using sorted() to sort lists

The most common iterables in Python are list-type objects. Let’s go over a few examples of sorting Python lists.

sample_list = sorted(['X', '1', 'Z'])
print(sample_list)

sample_list = sorted(['X', '9Y', 'Z'])
print(sample_list)

sample_list = sorted(['A', 'a', 'b', 'B'])
print(sample_list)

sample_list = sorted([-5, 2, -3, 1, 0, -4, 4, -2, -1, 5])
print(sample_list)

Output:

['1', 'X', 'Z']
['9Y', 'X', 'Z']
['A', 'B', 'a', 'b']
[-5, -4, -3, -2, -1, 0, 1, 2, 4, 5]

Do check out our detailed tutorial on the Python list.

Sort tuples using sorted()

Below is an example of a tuple sorted using the Python sorted() function.

sample_tup = sorted((10, 30, 20, -10, -20))
print(sample_tup)
print(type(sample_tup))

Output:

[-20, -10, 10, 20, 30]
<class 'list'>

You can see that the final output is a list.

Learn more about Python tuples here.

Sort a dictionary

A dictionary is a composite object which consists of a group of key-value pairs. Let’s see how to use the sorted() method to sort its elements.

sample_dict = {'function': 'sorted()', 'params': 3, 'arg1': 'iterable', 'arg2': 'key', 'arg3': 'reverse', 'return value': 'list'}
print(sample_dict)
print(sorted(sample_dict))

Output:

{'function': 'sorted()', 'params': 3, 'arg1': 'iterable', 'arg2': 'key', 'arg3': 'reverse', 'return value': 'list'}
['arg1', 'arg2', 'arg3', 'function', 'params', 'return value']

The dictionary values are sorted based on the “key” field. You can read more about the Python dictionary here.

Sort in reverse direction

Now, we’ll use the 2nd argument of the sorted function. Let’s see what impact does it have on the sorted output.

sample_str = ['Modi', 'Trump', 'Putin', 'Jinping']
print("Default sort: ", sorted(sample_str))
print("Reversed sort: ", sorted(sample_str, reverse = True))

sample_list = [5, 17, 37, 3, 13]
print("\nDefault sort: ", sorted(sample_list))
print("Reversed sort: ", sorted(sample_list, reverse = True))

sample_tup = (-1, -2, 2, 1, 0)
print("\nDefault sort: ", sorted(sample_tup))
print("Reversed sort: ", sorted(sample_tup, reverse = True))

sample_dict = {'function': 'sorted()', 'params': 3, 'arg1': 'iterable', 'arg2': 'key', 'arg3': 'reverse', 'return value': 'list'}
print("\nDefault sort: ", sorted(sample_dict))
print("Reversed sort: ", sorted(sample_dict, reverse = True))

Output:

Default sort: ['Jinping', 'Modi', 'Putin', 'Trump']
Reversed sort: ['Trump', 'Putin', 'Modi', 'Jinping']

Default sort: [3, 5, 13, 17, 37]
Reversed sort: [37, 17, 13, 5, 3]

Default sort: [-2, -1, 0, 1, 2]
Reversed sort: [2, 1, 0, -1, -2]

Default sort: ['arg1', 'arg2', 'arg3', 'function', 'params', 'return value']
Reversed sort: ['return value', 'params', 'function', 'arg3', 'arg2', 'arg1']

Sort using key

We can also provide a third argument to the Python sorted function. It can help us change the way the default function works.

For example, by default, it sorts a string based on the ASCII values. We can alter it to sort based on the length of the literal.

sample_str = ['Modi', 'Trump', 'Putin', 'Jinping']
print("Default sort: ", sorted(sample_str))
# We are passing the built-in len() method as the sort key
print("Key-based sort: ", sorted(sample_str, key = len))

Output:

Default sort: ['Jinping', 'Modi', 'Putin', 'Trump']
Key-based sort: ['Modi', 'Trump', 'Putin', 'Jinping']

Similarly, the sorted() function sorts a dictionary by its “key” field. With the sorted-key option, we can sort it based on the “value” field.

sample_dict = {'andi': 65, 'george': 34, 'elvis': 44, 'david': 25, 'caleb': 18, 'broady': 27}
print("\nDefault sort: ", sorted(sample_dict))
# Let's sort a dictionary by value
print("Key-based sort: ", sorted(sample_dict, key = lambda sample_dict: sample_dict[1]))

Output:

Default sort: ['andi', 'broady', 'caleb', 'david', 'elvis', 'george']
Key-based sort: ['david', 'caleb', 'george', 'elvis', 'andi', 'broady']

We’ve used Python lambda in the above example. It is used to create a tiny anonymous function that operates inline.

Sorted() function on mixed data types

We’ve earlier told you that the sorted() function doesn’t support the sorting of mixed types. Let’s see what exactly happens when you call it on an iterable having distinct objects.

Check out the below example:

mixed_type_list = ['a', 1, 'x', -3]
print(sorted(mixed_type_list))

Output:

TypeError: '<' not supported between instances of 'int' and 'str'

Sorted() vs. list sort()

There are some obvious differences between the two sort functions:

  • The sorted() function is richer in functionality as it can sort iterable of any type given as input. The sort method is strictly for the list.
  • Python sorted() function creates a new range object with the elements of the original list in the sorted order. The List.sort() method does an in-place sorting and modifies the source list.

If you have multiple lists (e.g. employees and their salary lists) that you have to combine, Python zip is the function you should use.

How to sort a user-defined type?

You will be glad to learn that we can even use Python’s sorted function to sort lists containing custom types. To demonstrate this, we’ll create a sequence of student classes and sort them based on different criteria.

"""
Desc: Create a user-defined type
Name: Student class
"""
class Student:
name = ''
rollno = 0
section = ''
subject = ''

def __init__(self, nm, rn, sn, ss):
self.name = nm
self.rollno = rn
self.section = sn
self.subject = ss

def __str__(self):
return 'St[name=%s, rollno=%s, section=%s, subject=%s]' % (self.name, self.rollno, self.section, self.subject)

"""
Desc: Let's have a list of student objects as follows:
"""
st1 = Student('Saba', 1, '1A', 'EVS')
st2 = Student('Ila', 2, '1B', 'Science')
st3 = Student('Kim',3, '2A', 'Maths')
st4 = Student('Kim',4, '2B', 'GK')

stu_list = [st1, st2, st3, st4]

"""
Desc: Sorting list of students based on rollno
"""
def get_stu_rollno(st):
return st.rollno

stu_list_by_rollno = sorted(stu_list, key=get_stu_rollno)

print("List of students ordered by rollno: ")
for st in stu_list_by_rollno:
print(st)

"""
Desc: Sorting list of students based on section
"""
def get_stu_section(st):
return st.section

stu_list_by_section = sorted(stu_list, key=get_stu_section)

print("\nList of students ordered by section: ")
for st in stu_list_by_section:
print(st)

Output:

List of students ordered by rollno: 
St[name=Saba, rollno=1, section=1A, subject=EVS]
St[name=Ila, rollno=2, section=1B, subject=Science]
St[name=Kim, rollno=3, section=2A, subject=Maths]
St[name=Kim, rollno=4, section=2B, subject=GK]

List of students ordered by section: 
St[name=Saba, rollno=1, section=1A, subject=EVS]
St[name=Ila, rollno=2, section=1B, subject=Science]
St[name=Kim, rollno=3, section=2A, subject=Maths]
St[name=Kim, rollno=4, section=2B, subject=GK]

Must Read: Search Key in Dictionary

Summary

You’ve now sensed the power of the Python sorted function. And now it’s your turn to taste it by using it in real applications.

If you have any queries, do let us know. We wish you all the best.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article python xrange vs. range function Python XRange vs Range
Next Article Print Diamond pattern shape using Range Print Diamond Pattern Using Range()

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x