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 List Sort Method
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 List Sort Method

Last updated: Nov 23, 2023 11:24 am
By Meenakshi Agarwal
Share
5 Min Read
Python List Sort Method Usage with Examples
SHARE

From this tutorial, you will be learning about the Python list Sort method. You will see how to use it with lists with the help of examples.

Contents
List Sort MethodHow does the Sort method work?Sort Method ExamplesSort a list of numbersSort a list of lettersSort a list of strings in PythonSort list by a key function

Note: The syntax used in the below section is for Python 3. You can change it to any other version of Python.

Python List Sort() Explained

In order to learn more about List features and methods – Read from our in-depth guide on Python List.

List Sort Method

The sort method performs the sorting of list elements in either ascending or descending directions. Its syntax is as follows:

# Syntax - How to use sort method.
List_name.sort(key = …, reverse = ...)

When the sort() gets called without arguments, it sorts in ascending order by default. It doesn’t have a return value.

It merely returns to the next line without returning any output.

Please note that it is not related to the built-in sorted() function. The sort method mutates or modifies an old list whereas sorted() creates a new sorted sequence.

How does the Sort method work?

When we call the Python sort method, it traverses the list of elements in a loop and rearranges them in ascending order when there are no arguments.

If we specify “reverse = true” as an argument, then the list gets sorted in descending order.

The primary parameter is the steps that the method must go through when sorting through a list of elements. The value given to the key can be a function or a simple calculation etc.

The flowchart for the mechanism is as follows:

Python List Sort Flowchart

Sort Method Examples

In order to understand how can we sort a list in Python, let’s check out different examples. We need to go through a variety of use cases to understand the sorting concept.

Sort a list of numbers

a. Sorting a list of numbers in ascending order

Natural_numbers = [1,4,23,3,2,1,0,9,7]

Natural_numbers.sort()

print (Natural_numbers)

Output:

[0, 1, 1, 2, 3, 4, 7, 9, 23]

b. Sorting a list of numbers in descending order

Natural_numbers = [1,23,4,25,22,3,4,5,9,7,5]

Natural_numbers.sort(reverse = True)

print (Natural_numbers)

Output:

[25, 23, 22, 9, 7, 5, 5, 4, 4, 3, 1]

While here you get to see a variety of usage of the sort method, understanding the Python zip function would still be worth reading. It is a powerful tool that has many applications apart from sorting multiple lists in parallel.

Sort a list of letters

a. Sorting a list of letters in Python (ascending order)

Vowels = ["a", "u", "i", "o", "e"]

Vowels.sort()

print (Vowels)

Output:

['a', 'e', 'i', 'o', 'u']

b. Sorting a list of letters in Python (descending order)

Vowels = ["a", "u", "i", "o", "e"]

Vowels.sort(reverse = True)

print (Vowels)

Output:

['u', 'o', 'i', 'e', 'a']

Sort a list of strings in Python

a. Sorting a list of strings in ascending order

Fruits = ["Apple", "Banana", "Tomato", "Grapes"]

Fruits.sort()

print (Fruits)

Output:

['Apple', 'Banana', 'Grapes', 'Tomato']

b. Sorting a Python list in descending order

Fruits = ["Apple", "Banana", "Tomato", "Grapes"]

Fruits.sort(reverse = True)

print (Fruits)

Output:

['Tomato', 'Grapes', 'Banana', 'Apple']

Sort list by a key function

a. Sort a list by a key function (ascending)

# Let's sort on the basis of 2nd element
def keyFunc(item):
    return item[1]

# Unordered list
unordered = [('b', 'b'), ('c', 'd'), ('d', 'a'), ('a', 'c')]

# Order list using key
unordered.sort(key=keyFunc)

# Output the sorted list
print('Ordered list:', unordered)

Output:

Ordered list: [('d', 'a'), ('b', 'b'), ('a', 'c'), ('c', 'd')]

b. Sorting a list using a key function (descending)

# Let's sort on the basis of 2nd element
def keyFunc(item):
    return item[1]

# Unordered list
unordered = [('b', 'b'), ('c', 'd'), ('d', 'a'), ('a', 'c')]

# Order list using key in the reverse direction
unordered.sort(key=keyFunc, reverse = True)

# Output the sorted list
print('Ordered list:', unordered)

Output:

Ordered list: [('c', 'd'), ('a', 'c'), ('b', 'b'), ('d', 'a')]

Must Read: Sorting a Dictionary in Python

Best,

TechBeamers

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 List Clear Method Explained with Examples List Clear Method in Python
Next Article Python List Remove Method Explained with Examples List Remove Method in Python

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