Sorting in python


Sorting in python

Sorting means arranging a large number of values in a specific order such as ascending and descending, alphabetical, distance, etc. Python provides built-in functions that offer powerful features to do basic sorting or customize ordering at a smooth level. Python has a built-in sort() list method that modifies it in-place and a sorted() built-in function that builds a new sorted list from an iterable.

list.sort()

The easiest way to sort elements of a list is by using the built-in sort() function. It modifies the values of the original list in-place and returns None. The sort() method must be called on a list; it does not work on any other iterable. When it is called, it traverses the list elements in a loop and rearranges them. As the sort() method does not need to create a new list, so has a little faster and efficient execution as the elements to sort is already in a list. The syntax of the sort() method is:

list.sort(key = …, reverse = …)

If the sort() gets called without any parameters, it sorts the list in the ascending order by default. However, it can be customized through optional keyword arguments.

    • reverse (optional):- If “reverse = true”, then the list gets sorted in the descending order. By default its value is False.
    • key (optional):- key parameter defines the base criteria for sort. Its value should be a function that transforms each element before comparison.
#numeric list
num_list = [5, 2, 3, 1, 4]
num_list.sort()
print(num_list)
#Output: [1, 2, 3, 4, 5]

#alphabetic list
str_list = ['e', 'a', 'U', 'o', 'I']
str_list.sort()
print(str_list)
#Output: ['I', 'U', 'a', 'e', 'o']
#python sorting uses  the Unicode Code Point of the first letter in each string to determine sort order.

#boolean list
bool_list = [True, 1, 0, num_list == str_list, 'A' >= 'a']
print(bool_list) 
print(bool_list.sort())
print(bool_list)
#Output: [True, 1, 0, False, False]
         None
         [0, False, False, True, 1]

#mixed list
mix_list = ['33',44,47,'12',True]
mix_list.sort()
#Output: TypeError: '<' not supported between instances of 'int' and 'str'

#sorting list in reverse direction
num_list.sort(reverse = True) #sorting numeric list in descending 
print(num_list)
#Output: [5, 4, 3, 2, 1]

str_list.sort(reverse = True) #sorting alphabetic list in descending 
print(str_list)
#Output: ['o', 'e', 'a', 'U', 'I']

#custom key sorting
hi_list = ['Hi','Hello','Howdy','Hey']
hi_list.sort(key = len, reverse = True)
#Output: ['Hello', 'Howdy', 'Hey', 'Hi']
#length of each element in the list is determined by len() and then returned in descending order.

str_list.sort(key = str.lower)
print(str_list)
#Output: ['a', 'e', 'I', 'o', 'U']
#key converted entire string to lowercase while sorting

#Nested list
nested_list = [[6, 9], [3, 23], [2, 3], [24, 16], [1, 57]]
nested_list.sort() #sorting according to first element of sublist
print(nested_list)
#Output: [[1, 57], [2, 3], [3, 23], [6, 9], [24, 16]]


#random list
random_list = [(2, 3), (3, 1), (4, 2), (1, 4)]
random_list.sort(key = lambda ele : ele[1]) #sorting according to second element of subtuple
print(random_list)
#Output: [(3, 1), (4, 2), (2, 3), (1, 4)]


#custom list
custom_list = [
    {'Name': 'michael', 'Age': 32},
    {'Name': 'Theo', 'Age': 24},
    {'Name': 'ana', 'Age': 22},
    {'Name': 'Landon', 'Age': 27}
]

custom_list.sort(key = lambda ele : ele.get('Name').lower()) #sorting according to "Name" key of subdictionary 
print(custom_list)
#Output: [
    {'Name': 'ana', 'Age': 22}, 
    {'Name': 'landon', 'Age': 27},
    {'Name': 'michael', 'Age': 32},
    {'Name': 'Theo', 'Age': 24}
]

def get_key(key):
   return key.get('Age') #sorting according to "Age" key of subdictionary 
custom_list.sort(key = get_key)
print(custom_list)
#Output: [
    {'Name': 'ana', 'Age': 22},
    {'Name': 'Theo', 'Age': 24},
    {'Name': 'landon', 'Age': 27},
    {'Name': 'michael', 'Age': 32}
]

sorted()

The sorted() built-in method performs the same as sort().  The difference is that it takes an iterable and returns a sorted list containing the items from the iterable, without modifying the original iterable. It provides the functionality to sort the objects of different data types. It performs the same as sort(). The difference is that it takes iterables The sorted function syntax is:

sorted(iterable, key = None, reverse = False)

Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort and has O(n log n) time complexity. If sorted() is called with no additional arguments then elements of iterable are sorted in ascending order.  Just list sort(), sorted() also has key and reverse optional keyword arguments that produce the same robust functionality.

    • iterable (required):-  sequence (list, tuple, string) or collection (dictionary, set) or any other iterator that needs to be sorted.
    • reverse (optional):- If “reverse = true”, then the iterable gets sorted in the descending order. By default its value is False.
    • key (optional):- key parameter defines the base criteria for sort. Its value should be a function that transforms each element before comparison.

Sorting List

#numeric list 
num_list = [5, 2, 3, 1, 4] 
print("Sorted list:",sorted(num_list))
print("Original list:",num_list)
#Output: Sorted list: [1, 2, 3, 4, 5]
         Original list: [5, 2, 3, 1, 4] # the initial values were unchanged

#alphabetic list 
sorted_str_list = sorted(['A', 'a', 'b', 'B'], key=str.lower) 
print("sorted_str_list:",sorted_str_list) 
#Output: sorted_str_list: ['A', 'B', 'a', 'b'] 

#random list 
random_list = [(2, 3), (3, 1), (4, 2), (1, 4)] 
print(sorted(random_list, key = lambda ele : ele[1], reverse=True)) #sorting according to second element of subtuple 
#Output: [(1, 4), (2, 3), (4, 2), (3, 1)]

Apart from the list, in python, there are also other iterables like tuple, string, set, dictionary, etc. According to the definition, sorted() method always returns a new list even though the input type is any iterable. Thus to match the input type, the returned object can be cast to input type iterable.

Sorting Tuple

#numeric tuple
num_tuple = (6, 9, -1, 3, 1, -10)
sorted_num_tuple = sorted(num_tuple) 
print("original num_tuple:",num_tuple,"type:",type(num_tuple))
print("sorted_num_tuple:",sorted_num_tuple,"type:",type(sorted_num_tuple))
#Output: original num_tuple: (6, 9, -1, 3, 1, -10) type: <class 'tuple'>   
         sorted_num_tuple: [-10, -1, 1, 3, 6, 9] type: <class 'list'>

#alphabetic tuple
str_tuple = ('P','y','t','h','o','n')
sorted_str_tuple = tuple(sorted(str_tuple)) #type converting sorted list to tuple
print("original str_tuple:",str_tuple,"type:",type(str_tuple)) 
print("sorted_str_tuple:",sorted_str_tuple,"type:",type(sorted_str_tuple))
#Output: original str_tuple: ('P', 'y', 't', 'h', 'o', 'n') type: <class 'tuple'>
         sorted_str_tuple: ('P', 'h', 'n', 'o', 't', 'y') type: <class 'tuple'>

#Nested tuple
nested_tuple = ((1,'c'),(2,'a'),(3,'d'),(4,'e'),(5,'b'))
print(tuple(sorted(nested_tuple,reverse = True,key = lambda ele: ele[1]))) #sorting according to second element of subtuple 
#Output: ((4, 'e'), (3, 'd'), (1, 'c'), (5, 'b'), (2, 'a'))

Sorting String

Each element means each letter of the sentence of the string including spaces will get rearrange using sorted() method instead of each word.

string = "Python for You"
print(sorted(string))
print("type:",type(string))
#Output: [' ', ' ', 'P', 'Y', 'f', 'h', 'n', 'o', 'o', 'o', 'r', 't', 'u', 'y']      
         type: <class 'list'>

print(sorted(string,key = str.lower))
#Output: [' ', ' ', 'f', 'h', 'n', 'o', 'o', 'o', 'P', 'r', 't', 'u', 'y', 'Y']

For rearranging each word instead of each character, split() built-in string method can be used, converting sentence into a list of strings.

string = "Python for You"
print(sorted(string.split()))
#Output: ['Python', 'You', 'for']

print(string.split().sort()) 
#Output: ['Python', 'You', 'for']

sorted_string = str(sorted(string.split()))
print(sorted_string)
print("type:",type(sorted_string))
#Output: ['Python', 'You', 'for']
         type: <class 'str'>

#join built in string method can be used to get a string from list
sorted_string = sorted(string.split())
final_sorted_string = " ".join(sorted_string) 
print(final_sorted_string)
print("type:",type(final_sorted_string))
#Output: Python You for
         type: <class 'str'>

Sorting Set

As a set is an unordered collection, casting resulting list back to a set might change the sorted order.

set1 = {45, 11, 30, 20, 55} 
sorted_list_of_set = sorted(set1) 
print(sorted_list_of_set) 
#Output: [11, 20, 30, 45, 55]

sorted_set = set(sorted_list_of_set)
print(sorted_set)
print("type:",type(sorted_set))
#Output: {11, 45, 20, 55, 30}
         type: <class 'set'>

Sorting Dictionary

Depending on the data passed on to the sorted() method, dictionaries can be sorted in two different ways in Python. The dictionaries are by default rearranged based on their “key” field by using the sorted() method.

#sorting by keys
veggies_prices_dict = {'Carot': 35, 
                       'Cabbage': 10, 
                       'Tomato': 20, 
                       'Potato': 30, 
                       'Onion': 60, 
                       'Lady Finger': 40}

print(sorted(veggies_prices_dict))
#Output: ['Cabbage', 'Carot', 'Lady Finger', 'Onion', 'Potato', 'Tomato']

print(sorted(veggies_prices_dict.keys())) 
#Output: ['Cabbage', 'Carot', 'Lady Finger', 'Onion', 'Potato', 'Tomato'] 

print(sorted(veggies_prices_dict.items())
#Output: [('Cabbage', 10), ('Carot', 35), ('Lady Finger', 40), ('Onion', 60), ('Potato', 30), ('Tomato', 20)]

print(sorted(veggies_prices_dict.items(), key = lambda value: value[0]))
#Output: [('Cabbage', 10), ('Carot', 35), ('Lady Finger', 40), ('Onion', 60), ('Potato', 30), ('Tomato', 20)]

print(sorted(veggies_prices_dict, reverse = True)) 
#Output: ['Tomato', 'Potato', 'Onion', 'Lady Finger', 'Carot', 'Cabbage']

print(sorted(veggies_prices_dict.items(),reverse=True))
#Output: [('Tomato', 20), ('Potato', 30), ('Onion', 60), ('Lady Finger', 40), ('Carot', 35), ('Cabbage', 10)]

print(sorted(veggies_prices_dict.items(), key = lambda value: value[0],reverse=True))
#Output: [('Tomato', 20), ('Potato', 30), ('Onion', 60), ('Lady Finger', 40), ('Carot', 35), ('Cabbage', 10)] 

#sorting by values
print(sorted(veggies_prices_dict.values()))
#Output: [10, 20, 30, 35, 40, 60]

print(sorted(veggies_prices_dict.items(), key = lambda value: value[1]))
#Output: [('Cabbage', 10), ('Tomato', 20), ('Potato', 30), ('Carot', 35), ('Lady Finger', 40), ('Onion', 60)]

print(sorted(veggies_prices_dict.values(), reverse = True)) 
#Output: [60, 40, 35, 30, 20, 10]

print(sorted(veggies_prices_dict.items(), reverse=True, key = lambda value: value[1]))
#Output: [('Onion', 60), ('Lady Finger', 40), ('Carot', 35), ('Potato', 30), ('Tomato', 20), ('Cabbage', 10)]

 

%d bloggers like this: