Sorting means arranging the set of values in either an increasing or decreasing manner. There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. We can sort values in Python using built-in functions like sorted() or by using the sort() method for lists.
Sorted() Method
sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable, such as a list, tuple or string. The original iterable remains unchanged.
Example 1: Sorting Different Data Types Using sorted()
This example demonstrates how to sort different types of data structures like lists, tuples, strings, dictionaries, sets and frozen sets using the sorted() function.
Python
# List
a = ['g', 'e', 'e', 'k', 's']
print(sorted(a))
# Tuple
tup = ('g', 'e', 'e', 'k', 's')
print(sorted(t))
# String-sorted based on ASCII translations
a = "geeks"
print(sorted(a))
# Dictionary
d = {'g': 1, 'e': 2, 'k': 3, 's': 4}
print(sorted(d))
# Set
s = {'g', 'e', 'e', 'k', 's'}
print(sorted(s))
frozen_set = frozenset(('g', 'e', 'e', 'k', 's'))
print(sorted(frozen_set))
Output['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']
Explanation: The sorted() function returns a new sorted list from the iterable provided. It works with any iterable object and sorts them based on their natural order. For dictionaries, the keys are sorted and for sets and frozen sets, the unique elements are sorted.
Example 2: Using predefined function as key-parameter
This code shows how to use the key parameter with a predefined function (len()) to sort a list of strings based on their length.
Python
a = ["apple", "ball", "cat", "dog"]
print("without key parameter:", sorted(a))
print("with len as key parameter:", sorted(a, key=len))
Outputwithout key parameter: ['apple', 'ball', 'cat', 'dog']
with len as key parameter: ['cat', 'dog', 'ball', 'apple']
Explanation: The key parameter is used to specify a function to be applied to each element before sorting. Here, the len() function is used to sort a list of strings based on their lengths. The output is sorted by the number of characters in each string rather than by the lexicographical order of the strings.
Example 3: Using the user-defined function for the key parameter
This example explains how to use the key parameter with custom user-defined functions to sort a list of tuples based on either the name or the marks.
Python
a = [("Ramesh",56),("Reka",54),("Lasya",32),("Amar",89)]
# defining a user-defined function which returns the first item(name)
def by_name(ele):
return ele[0]
# defining a user-defined function which returns the second item(marks)
def by_marks(ele):
return ele[1]
print("without key parameter:", sorted(a))
print("with by_name as key parameter:", sorted(a, key=by_name))
print("with by_marks as key parameter:", sorted(a, key=by_marks))
Output
without key parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with by_name as key parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with by_marks as key parameter: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
Explanation: In this code, the sorted() function is used with user-defined functions (by_name and by_marks) passed through the key parameter. This allows us to customize how sorting is done based on specific attributes. In this example, a list of tuples containing student names and marks is sorted first by the name (alphabetically) and then by the marks (numerically).
Example 4: Using reverse Parameter
This example demonstrates how to use the reverse=True parameter to sort data in descending order, along with the regular sorted() function.
Python
a = ["geeks","for","geeks"]
print("without key parameter:", sorted(a))
print("with len as key parameter:", sorted(a, reverse=True))
Outputwithout key parameter: ['for', 'geeks', 'geeks']
with len as key parameter: ['geeks', 'geeks', 'for']
Explanation: reverse parameter is demonstrated in the sorted() function. When reverse=True, the function sorts the data in descending order instead of the default ascending order. This example sorts a list of strings in reverse order based on their lexicographical order, meaning that the list is ordered from Z to A instead of A to Z.
Example 5: Using key and reverse Parameters
This example combines the use of both key and reverse parameters to sort data based on user-defined functions with the option to sort in ascending or descending order.
Python
a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]
# defining a user-defined function which returns the first item(name)
def by_name(ele):
return ele[0]
# defining a user-defined function which returns the second item(marks)
def by_marks(ele):
return ele[1]
print("without key and reverse:", sorted(a))
print("with key and reverse parameter:", sorted(a, key=by_name, reverse=False))
print("with key and reverse parameter:", sorted(a, key=by_name, reverse=True))
print("with key and reverse parameter:", sorted(a, key=by_marks, reverse=False))
print("with key and reverse parameter:", sorted(a, key=by_marks, reverse=True))
Output
without key and reverse: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with key parameter and reverse parameter: [('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
with key parameter and reverse parameter: [('Reka', 54), ('Ramesh', 56), ('Lasya', 32), ('Amar', 89)]
with key parameter and reverse parameter: [('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
with key parameter and reverse parameter: [('Amar', 89), ('Ramesh', 56), ('Reka', 54), ('Lasya', 32)]
Explanation: This example combines both the key and reverse parameters in the sorted() function. The key parameter allows sorting based on a custom criterion (like student names or marks) and the reverse parameter allows for sorting in descending order. By using both, the list of student tuples can be sorted by name or marks, in ascending or descending order, depending on the specified flags.
Sort() Method
sort() method is a list method that sorts the list in place. Unlike the sorted() function, it does not return a new list but modifies the original list.
Example 1: Basic List Sorting Using sort()
This example demonstrates how to sort a list of strings in ascending order using Python's sort() method. It modifies the list in place.
Python
a = ["geeks", "for", "geeks"]
# using the sort method to sort the items
a.sort()
print("Sorted list:", a)
OutputOriginal list: ['geeks', 'for', 'geeks']
Sorted list: ['for', 'geeks', 'geeks']
Explanation: The sort() method sorts the items of the list in lexicographical (alphabetical) order. Since no key or reverse parameter is provided, it performs a default ascending order sort. The sorting is done directly on the original list, meaning no new list is created.
Example 2: Using a predefined function as the key parameter
This example demonstrates how to sort a list of strings based on their length using the key parameter with the predefined len() function.
Python
a = ["apple", "ball", "cat", "dog"]
# using the len() as key parameter and sorting the list
a.sort(key=len)
print("Sorting with len as key parameter:", a)
OutputSorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']
Explanation: In this example, the sort() method is used with the key parameter, where key=len sorts the list based on the length of each string. The key parameter tells Python to compare the items by their length rather than their value. This results in sorting the list from the shortest string to the longest.
Example 3: Using a user-defined function as the key parameter
This code demonstrates sorting a list of tuples by custom criteria: the student’s name and marks, using user-defined functions for sorting.
Python
def by_name(ele):
return ele[0]
# defining a user-defined function which returns the second item(marks)
def by_marks(ele):
return ele[1]
a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]
# sorting by key value as by_name function
a.sort(key=by_name)
print(a)
a = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]
# sorting by key value as by_marks function
a.sort(key=by_marks)
print(a)
Output:
[('Amar', 89), ('Lasya', 32), ('Ramesh', 56), ('Reka', 54)]
[('Lasya', 32), ('Reka', 54), ('Ramesh', 56), ('Amar', 89)]
Explanation: In this example, the sort() method uses a key parameter that is set to user-defined functions. The function by_name sorts the list of tuples by the first element (the name) and the function by_marks sorts by the second element (the marks). This allows sorting based on the desired attribute, either name or marks.
Example 4: Using reverse parameter
This code illustrates how to sort a list in descending order using the reverse=True parameter.
Python
a = ["geeks", "for", "geeks"]
a.sort(reverse=True)
print("with reverse parameter", a)
Outputwith reverse parameter ['geeks', 'geeks', 'for']
Explanation: The sort() method with reverse=True sorts the list in descending order. This means the largest elements come first and the smallest elements come last. It modifies the original list and sorts it in place. The reverse parameter effectively reverses the result of the default ascending order sort.
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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 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
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ 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