Sort in Python- An Easy Way to Learn

Sort in Python- An Easy Way to Learn

27 Aug 2024
Beginner
496 Views
17 min read

Sort in Python

Sort in Python is an important and flexible technique that allows you to structure your data. To put it another means, sort in Python simply involves organizing it into a certain format or order. 

In this Python tutorial, we will learn what is sort in Python?, what is the List sort() method?, how to use the sort() method, the sorting of operator module in Python functions, the difference between the sort() and sorted() methods, and many more.

What is Sort in Python?

Sort in Python is a common operation in programming languages. It involves arranging elements of a list or other iterable types in a specific order. Let's understand this method in some key points:

  • Python provides two main sorting methods: sorted() and sort().
  • The sorted() method is used to return a new sorted list.
  • The sort() method is used to sort a list in place.
  • The key parameter allows for custom sorting by defining a function that determines the sort order.
  • Sorting in reverse order can be done by setting the reverse parameter to True, enabling descending-order sorting.
  • Python's sorting is stable, which means that it keeps the order of elements equal based on the sorting criterion.

What is Sort in Python?

Read More
Python Career Guide: Is it worth learning in 2024?
10 Python Developer Skills You Must Know in 2024
Python Developer Roadmap: How to Become a Python Developer?

What is the List sort() Method?

The sort() method in Python sorts the elements of a list in place, meaning it rearranges the original Python list in ascending or descending order according to the specified criteria. This method does not return a new list but rather modifies the existing one.

Syntax

list_name.sort(reverse=..., key=... )

Important points should be remembered here:

  • list_name: Name of the list you are operating with.
  • sort(): method of arranging elements in a list either in ascending or descending order and accepting two parameters.
  • reverse: It is a boolean (True or False) value parameter used to arrange a list in ascending or descending order. The default value is False.
  • The default value is false, which means it arranges the list in ascending order.
  • If we set reverse to true, the list will be arranged in descending order.
  • Key: It requires a function or method that specifies any particular sorting criteria you may have.
Note- sort() function returns None, indicating that there is no return value because it only updates the original list. It doesn't return a new list.

1. Sorting a List in Ascending Order

To sort a list in ascending order, you can use the sort() method or the sorted() function in Python.

Example

# Defining a list of a numbers
my_Num = [10, 4, 6, 14, 18, 7, 94, 100, 34]

#sorting the list in-place in ascending order
my_Num.sort()

#print the sorted list 
print(my_Num)

Output

[4, 6, 7, 10, 14, 18, 34, 94, 100]

Explanation

In this example,
  • We have declared a list of my_Num with numbers.
  • Use the sort() method, which prints the list in ascending order.

Example- Sorting a List of String Values in Alphabetical Ascending Order.

# a list of strings
family_mem = ["Raghav", "John","Anvadya", "Sam"]

#sort list in-place in alphabetical order
family_mem.sort()

#print modified list
print(family_mem)

Output

['Anvadya', 'John', 'Raghav', 'Sam']

Explanation

In this example,
  • We declare a list of family_mem with string values.
  • We use sort() and print the original list in alphabetical ascending order.

2. Sorting a List in Descending Order

To sort a list in descending order, use the sort(reverse=True) method or the sorted(list, reverse=True) function in Python.

Example

# Defining a list of positive integer numbers
my_numb = [10, 8, 3, 24, 37, 7, 13, 99, 52]

#sorting list in-place in descending order
my_numb.sort(reverse=True)

#print modified list
print(my_numb)

Output

[99, 52, 37, 24, 13, 10, 8, 7, 3]

Explanation

In this example,
  • We declare a list of my_numb with positive integer numbers.
  • We call the sort() method with (reverse=True) that prints the list in descending order.

3. Sorting With Custom Keys

To sort a list with custom keys, use the sort(key=custom_function) method or sorted(list, key=custom_function) function, where custom_function defines the sorting logic.

Example

# declaring a list of string value
languages = ["Python", "Swift","Java", "C", "Go"]

#Assigning len() function to key parameter
languages.sort(key=len)

print(languages)

Output

['c', 'Go', 'Java', 'Swift', 'Python']

Explanation

In this example,
  • We have declared a list of languages that contain string values.
  • In this languages. sort(key=len) line, we assign len() function to key parameter that prints the result in ascending order according to the length of the string values.

Sorting with Operator Module Functions

Python's operator module provides a collection of efficient functions that correspond to conventional operators. These functions can be used as the primary parameter in sorting operations to achieve more sophisticated sorts with simpler syntax. Here are some common functions for the operator module:

  1. operator.itemgetter()
  2. operator.attrgetter()
  3. operator.methodcaller()

1. operator.itemgetter()

The operator.itemgetter() function is used to sort a list based on specific item in a list of tuples or dictionaries. It allows you to sort by multiple fields by specifying multiple indices.

Example

import operator

# List of tuples
students = [("Aman", 90), ("Ankita", 80), ("Rajesh", 95)]

# Sort by the second element (the score)
sorted_students = sorted(students, key=operator.itemgetter(1))
print(sorted_students)

Output

[('Ankita', 80), ('Aman', 90), ('Ankita', 95)]

Explanation

In this example,
  • We import the operator module and declare a list of tuples name students.
  • sorted_students = sorted(students, key=operator.itemgetter(1)) line, we assign operator.itemgetter() function in key parameter and prints the results.

2. operator.attrgetter()

The operator.attrgetter() is used to sort objects based on their attributes, providing a straightforward method to sort by specific properties. It also supports handling nested attributes, which is particularly useful for managing complex object structures.

Example

import operator

# Define a class with attributes
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# List of Person objects
people = [Person("Aman", 30), Person("Ram", 25), Person("Ankita", 35)]

# Sort by the 'age' attribute
sorted_people = sorted(people, key=operator.attrgetter('age'))

print([person.name for person in sorted_people]) 

Output

['Ram', 'Aman', 'Ankita']

Explanation

In this example,

  • We have defined a class Person with attributes and a list of name people that contains Person objects.
  • sorted_people = sorted(people, key=operator.attrgetter('age')) line, we assign operator.attrgetter() operator in key parameter and prints the results.

3. operator.methodcaller()

The operator.methodcaller() is used for sorting elements based on the result of calling a specified method on each element.

Example

import operator

# List of strings
words = ["banana", "apple", "cherry"]

# Sort by the length of each string
sorted_words = sorted(words, key=operator.methodcaller('len'))

print(sorted_words)

Output

['apple', 'banana', 'cherry']

Explanation

In this example,
  • We have declared a list of words that contains the string values.
  • sorted_words = sorted(words, key=operator.methodcaller('len')) line, we assign operator.methodcaller() with len() function in key parameter and print the results.

Difference Between sort() and sorted()

The sort() and sorted() methods are both used to sort the elements in a list. But they have some differences between them that are:

Difference Between sort() and sorted()

Featuressort() Methodsorted() Method
TypeIt is the method of listing objectsIt is a built-in function
Return ValueIt provides none (modifies the list in place)It provides a new sorted list
Modifies OriginalYesNo
UsageUsed when you want to sort a list in placeUsed when you need a new sorted list without altering the original
PerformanceGenerally faster for large lists since it sorts in place

Slightly slower due to the creation of a new list

Read More
Python Developer Salary
Top 50+ Python Interview Questions and Answers
Python Features: A Comprehensive Guide for Beginners
Conclusion
In Conclusion, Sort in Python is essential for organizing data, using the sort() method for in-place sorting or sorted() for generating a new sorted list. Both support custom sorting and descending order. The operator module's functions, like itemgetter() and attrgetter(), simplify complex sorting tasks. For developers, these tools streamline data management, enhance code readability, and improve efficiency in handling sorted data. If you want to learn Python thoroughly, ScholorHat provides a Free Python Programming Course for beginners to help you better understand other Python concepts.

FAQs

The sort() method sorts a list in place, modifying the original list, while the sorted() function returns a new sorted list without altering the original. 

To sort a list in ascending order in Python, you can use the sort() method, which modifies the original list, or the sorted() function, which returns a new sorted list while leaving the original list unchanged. 

You can sort a list in descending order in Python by using the sort() method with the reverse=True argument or the sorted() function with the same argument to return a new list sorted in descending order. 

The key parameter in sorting is used to specify a function that extracts a comparison key from each list element, allowing you to define custom sorting criteria based on specific attributes or transformations of the elements 

Sorting stability ensures that elements with equal values maintain their original order after sorting. It's important when the relative order of equal elements carries meaning or when performing multiple sorts on the same dataset. 

To handle sorting errors in Python, you can use a try-except block to catch exceptions like TypeError, which occurs when elements are not comparable. Ensure that all elements are of compatible types or provide a custom key function to avoid such errors.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this