How to Sort a Set of Values in Python? (original) (raw)
**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))
`
Output
without 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))
`
Output
without 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)
`
Output
Original 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)
`
Output
Sorting 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)
`
Output
with 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.