Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to Sort a Set of Values in Python?

How to Sort a Set of Values in Python?

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.

Sorted() Method

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




# List
list_of_items = ['g', 'e', 'e', 'k', 's']
print(sorted(list_of_items))
 
# Tuple
tuple_of_items = ('g', 'e', 'e', 'k', 's')
print(sorted(tuple_of_items))
 
# String-sorted based on ASCII
# translations
string = "Lazyroar"
print(sorted(string))
 
# Dictionary
dictionary = {'g': 1, 'e': 2, 'k': 3, 's': 4}
print(sorted(dictionary))
 
# Set
set_of_values = {'g', 'e', 'e', 'k', 's'}
print(sorted(set_of_values))
 
# Frozen Set
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']

 

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))


Output

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 marks
list_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 = ["Lazyroar","for","Lazyroar"]
 
print("Sorting without key parameter:",
      sorted(list_of_items))
 
print("Sorting with len as key parameter:",
      sorted(list_of_items, reverse=True))


Output

Sorting without key parameter: ['for', 'Lazyroar', 'Lazyroar']
Sorting with len as key parameter: ['Lazyroar', 'Lazyroar', '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 marks
list_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)]

Sort() Method

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 items
list_of_items = ["Lazyroar", "for", "Lazyroar"]
print("Original list:", list_of_items)
 
# using the sort method to sort
# the items
list_of_items.sort()
 
# displaying the list
print("Sorted list:", list_of_items)


Output

Original list: ['Lazyroar', 'for', 'Lazyroar']
Sorted list: ['for', 'Lazyroar', 'Lazyroar']

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 list
list_of_items.sort(key=len)
print("Sorting with len as key parameter:", list_of_items)


Output

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 marks
list_of_items = [("Ramesh", 56), ("Reka", 54),
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
 
# sorting by key value as by_name function
list_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 marks
list_of_items = [("Ramesh", 56), ("Reka", 54),
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
 
# sorting by key value as by_marks function
list_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 = ["Lazyroar", "for", "Lazyroar"]
 
print("original list:", list_of_items)
 
list_of_items.sort(reverse=True)
print("sorting with reverse parameter", list_of_items)


Output

original list: ['Lazyroar', 'for', 'Lazyroar']
sorting with reverse parameter ['Lazyroar', 'Lazyroar', 'for']

RELATED ARTICLES

Most Popular

Recent Comments