Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.
Python
# Initializing a list
a = [5, 1, 5, 6]
# Sort modifies the given list
a.sort()
print(a)
b = [5, 2, 9, 6]
# Sorted does not modify the given list
# and returns a different sorted list
bs = sorted(b)
print(b)
print(bs)
Output[1, 5, 5, 6]
[5, 2, 9, 6]
[2, 5, 6, 9]
This article will cover the basics of sorting lists in Python, including built-in functions, custom sorting, and sorting based on specific criteria.
Python Sorting Methods
Python sort()
Method
The sort()
method sorts the list in place and modifies the original list. By default, it sorts the list in ascending order.
Python
# Initializing a list
a = [5, 2, 9, 1, 5, 6]
# Sorting the list in ascending order
a.sort()
print("Sorted list (ascending):", a)
a.sort(reverse=True)
print("Sorted list (descending):", a)
OutputSorted list (ascending): [1, 2, 5, 5, 6, 9]
Sorted list (descending): [9, 6, 5, 5, 2, 1]
Python sorted()
Function
Python sorted() function returns a sorted list. It is not only defined for the list and it accepts any iterable (list, tuple, string, etc.). It does not modify the given container and returns a sorted version of it.
Python
# Initializing a list
a = [5, 2, 9, 1, 5, 6]
# Sorting the list in descending order
sa = sorted(a)
print("Sorted list (ascending):", sa)
sa = sorted(a, reverse=True)
print("Sorted list (descending):", sa)
OutputSorted list (ascending): [1, 2, 5, 5, 6, 9]
Sorted list (descending): [9, 6, 5, 5, 2, 1]
Sorting Other Containers :
- Sorting a tuple: The
sorted()
function converts the tuple into a sorted list of its elements. - Sorting a set: Since sets are unordered,
sorted()
converts the set into a sorted list of its elements. - Sorting a string: This will sort the characters in the string and return a list of the sorted characters.
- Sorting a dictionary: When a dictionary is passed to
sorted()
, it sorts the dictionary by its keys and returns a list of the keys in sorted order. - Sorting a list of tuples: The list of tuples is sorted primarily by the first element of each tuple, and secondarily by the second element if the first ones are identical.
Python
# Sorting a tuple
a = (10, 12, 5, 1)
print(sorted(a))
# Sorting a set
s = {'gfg', 'course', 'python'}
print(sorted(s))
# Sorting a string
st = 'gfg'
print(sorted(st))
# Attempting to sort a dictionary (it will sort the keys)
d = {10: 'gfg', 15: 'ide', 5: 'course'}
print(sorted(d))
# Sorting a list of tuples
l = [(10, 15), (1, 8), (2, 3)]
print(sorted(l))
Output[1, 5, 10, 12]
['course', 'gfg', 'python']
['f', 'g', 'g']
[5, 10, 15]
[(1, 8), (2, 3), (10, 15)]
Sorting User Defined Object
Example 1: Using a Separate Method
This code defines a Point
class with an initializer that sets the x
and y
coordinates for point objects. The myFun
function takes a point object and returns its x
coordinate. A list l
of Point
objects is created, and then sorted based on their x
values using the myFun
function as the key in the sort
method. Finally, it prints out the x
and y
coordinates of each Point
in the sorted list.
Python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def myFun(p):
return p.x
l = [Point(1, 15), Point(10, 5), Point(3, 8)]
l.sort(key=myFun)
for i in l:
print(i.x, i.y)
Example 2: Using a __lt__ Method
This version defines the __lt__
method within the Point
class and includes the necessary return statement, which compares the x
attribute of the instances. Now when you call l.sort()
, Python will use this __lt__
method to determine the order of Point
objects in the list based on their x
values. This will sort the points in ascending order by their x
coordinates, and the print output will reflect that order.
Python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
return self.x < other.x
l = [Point(1, 15), Point(10, 5), Point(3, 8)]
l.sort()
for i in l:
print(i.x, i.y)
Sorting with Custom Criteria
Sorting Based on Absolute Values
Sometimes you may want to sort numbers based on their absolute values while preserving their original signs. You can do this by using the key
parameter in both the sort()
method and the sorted()
function.
Python
a = [1, -5, 10, 6, 3, -4, -9]
# Sorting by absolute values in descending order
sa = sorted(a, key=abs, reverse=True)
print("Sorted by absolute values:", sa)
OutputSorted by absolute values: [10, -9, 6, -5, -4, 3, 1]
Custom Sorting with Lambda Functions
You can use lambda functions to define custom sorting logic. For example, if you want to sort a list of tuples based on the second element:
Python
# List of tuples
a = [(1, 'one'), (3, 'three'), (2, 'two')]
# Sorting by the second element of each tuple
sa = sorted(a, key=lambda x: x[1])
print("Sorted by second element:", sa)
OutputSorted by second element: [(1, 'one'), (3, 'three'), (2, 'two')]
When sorting lists, the choice between sort()
and sorted()
may depend on whether you want to maintain the original list. The sort()
method is generally faster since it sorts the list in place. However, if you need to keep the original order, use sorted()
.
Time Complexity
sort()
and sorted()
: Both have a time complexity of O(n log n).
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read