How to Sort a Set of Values in Python?

16 Jun, 2021
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. So, in this article, we will discuss some methods and criteria to sort the data in Python.
This is a pre-defined method in python which sorts any kind of object.
Syntax:
sorted(iterable, key, reverse)
In this method, we pass 3 parameters, out of which 2 (key and reverse) are optional and the first parameter i.e. iterable can be any iterable object This method returns a sorted list but does not change the original data structure.
Example 1:
Python3
# Listlist_of_items = ['g', 'e', 'e', 'k', 's']print(sorted(list_of_items)) # Tupletuple_of_items = ('g', 'e', 'e', 'k', 's')print(sorted(tuple_of_items)) # String-sorted based on ASCII# translationsstring = "geeks"print(sorted(string)) # Dictionarydictionary = {'g': 1, 'e': 2, 'k': 3, 's': 4}print(sorted(dictionary)) # Setset_of_values = {'g', 'e', 'e', 'k', 's'}print(sorted(set_of_values)) # Frozen Setfrozen_set = frozenset(('g', 'e', 'e', 'k', 's'))print(sorted(frozen_set))
  
['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']
 
Example 2:
 
Using predefined function as key-parameter. So the second parameter i.e. key is used to sort the given data structure by some predefined function such as len() or some user-defined function. It sorts the values in the data structure based on the function passed to the key parameter.
 
Python3
# using key parameter with pre-defined# function i.e. len() list_of_items = ["apple", "ball", "cat", "dog"] print("Sorting without key parameter:", sorted(list_of_items))print("Sorting with len as key parameter:", sorted(list_of_items, key=len))
Sorting without key parameter: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']
Example 3:
Using the user-defined function for the key parameter.
Python3
# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("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("Sorting without key parameter:", sorted(list_of_items)) print("Sorting with by_name as key parameter:",      sorted(list_of_items, key=by_name)) print("Sorting with by_marks as key parameter:",      sorted(list_of_items, key=by_marks))
Output
Sorting without key parameter: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
Sorting with by_name as key parameter: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
Sorting with by_marks as key parameter: [(‘Lasya’, 32), (‘Reka’, 54), (‘Ramesh’, 56), (‘Amar’, 89)]
Example 4:
So the 3rd parameter is reverse which is used to sort the iterable in descending or decreasing order.
Python3
# using key parameter reverse list_of_items = ["geeks","for","geeks"] print("Sorting without key parameter:",      sorted(list_of_items)) print("Sorting with len as key parameter:",      sorted(list_of_items, reverse=True))
Sorting without key parameter: ['for', 'geeks', 'geeks']
Sorting with len as key parameter: ['geeks', 'geeks', 'for']
Example 5:
Using all the three parameters
Python3
# using by_name and by_marks as key parameter# and making reverse parameter true # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("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("Sorting without key and reverse:", sorted(list_of_items)) print("Sorting with by_name as key parameter and reverse parameter as False:",      sorted(list_of_items, key=by_name, reverse=False))print("Sorting with by_name as key parameter and reverse parameter as True:",      sorted(list_of_items, key=by_name, reverse=True)) print("Sorting with by_marks as key parameter and reverse parameter as False:",      sorted(list_of_items, key=by_marks, reverse=False))print("Sorting with by_marks as key parameter and reverse parameter as True:",      sorted(list_of_items, key=by_marks, reverse=True))
Output
Sorting without key and reverse: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
Sorting with by_name as key parameter and reverse parameter as False: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
Sorting with by_name as key parameter and reverse parameter as True: [(‘Reka’, 54), (‘Ramesh’, 56), (‘Lasya’, 32), (‘Amar’, 89)]
Sorting with by_marks as key parameter and reverse parameter as False: [(‘Lasya’, 32), (‘Reka’, 54), (‘Ramesh’, 56), (‘Amar’, 89)]
Sorting with by_marks as key parameter and reverse parameter as True: [(‘Amar’, 89), (‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32)]
This method sorts the list in ascending order by default, and we can use the reverse parameter to sort in descending order. This method changes the original list and doesn’t return anything. 
Example 1:
Python3
# creating a list of itemslist_of_items = ["geeks", "for", "geeks"]print("Original list:", list_of_items) # using the sort method to sort# the itemslist_of_items.sort() # displaying the listprint("Sorted list:", list_of_items)
Original list: ['geeks', 'for', 'geeks']
Sorted list: ['for', 'geeks', 'geeks']
Example 2:
Using a predefined function as the key parameter
Python3
# using key parameter with pre-defined# function i.e. len() list_of_items = ["apple", "ball", "cat", "dog"] print("Original List:", list_of_items) # using the len() as key parameter and# sorting the listlist_of_items.sort(key=len)print("Sorting with len as key parameter:", list_of_items)
Original List: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']

Example 3:
Using a user-defined function as the key parameter
Python3
# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # 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]  # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh", 56), ("Reka", 54),                 ("Lasya", 32), ("Amar", 89)]print("original list:", list_of_items) # sorting by key value as by_name functionlist_of_items.sort(key=by_name)print("Sorting with by_name as key parameter:", list_of_items) # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh", 56), ("Reka", 54),                 ("Lasya", 32), ("Amar", 89)]print("original list:", list_of_items) # sorting by key value as by_marks functionlist_of_items.sort(key=by_marks)print("Sorting with by_marks as key parameter:", list_of_items)
Output
original list: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]
Sorting with by_name as key parameter: [(‘Amar’, 89), (‘Lasya’, 32), (‘Ramesh’, 56), (‘Reka’, 54)]
original list: [(‘Ramesh’, 56), (‘Reka’, 54), (‘Lasya’, 32), (‘Amar’, 89)]
Sorting with by_marks as key parameter: [(‘Lasya’, 32), (‘Reka’, 54), (‘Ramesh’, 56), (‘Amar’, 89)]
Example 4:
Using reverse parameter
Python3
# using key parameter reverse list_of_items = ["geeks", "for", "geeks"] print("original list:", list_of_items) list_of_items.sort(reverse=True)print("sorting with reverse parameter", list_of_items)
original list: ['geeks', 'for', 'geeks']
sorting with reverse parameter ['geeks', 'geeks', 'for']
simranarora5sos
Picked
Python
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm