In this article we will explore how to use Python tidy () function
Table of Contents
- Introduction
- Basic sorting using sorted()
- Using the key function with sorted()
- Sort custom objects using sorted()
- Conclution
Piton tidy () The function is a built-in function for ordering iterables.
It uses timsort as the sort algorithm, which is derived from merge sort and insertion sort.
Python syntax tidy () function is:
sorted(iterable, key=None, reverse=False)
where:
- iterable — can be any iterable Python object such as string, tuple, list, array, dictionaryand others.
- wrench — optional argument allowing to add a function (for example lambda function) as the sort key. default to Neither.
- counter — optional argument allowing the iterable to be reversed (for sorting in descending order) if set to TRUE. default to False.
He tidy () function process is defined as:
sorted(iterable) -> sorted list
There are many applications of the tidy () function, so let’s look at some basic examples.
Sort a list of numbers in ascending order
The simplest example is ordering a ready of numbers in ascending order:
#Create a list of numbers
nums = [3, 1, 9, 7, 5]#Sort the list of numbers
s_nums = sorted(nums)
#Print sorted list
print(s_nums)
and you should get:
[1, 3, 5, 7, 9]
Sort a list of numbers in descending order
Similar to the previous example, we’ll sort a list of numbers, but now in descending order:
#Create a list of numbers
nums = [3, 1, 9, 7, 5]#Sort the list of numbers
s_nums = sorted(nums, reverse=True)
#Print sorted list
print(s_nums)
and you should get:
[9, 7, 5, 3, 1]
Sort a list of strings
Piton tidy () The function can also sort lists with string elements in it.
The procedure with the classification of numbers is very simple and intuitive, and can be extended to the classification of strings.
Piton tidy () The function sorts the strings based on the first character of each string (for example, ‘apple’ It comes before ‘orange’ given that ‘a’ it is before ‘either’ in the alphabet).
Let’s take a look at an example:
#Create a list of strings
fruit = ['banana', 'pineapple', 'orange', 'apple']#Sort the list of strings
s_fruit = sorted(fruit)
#Print sorted list
print(s_fruit)
and you should get:
['apple', 'banana', 'orange', 'pineapple']
As you can see, the list of strings has been sorted alphabetically (ascending) based on the first character of the string.
You can also sort a list of strings in descending order by setting the optional counter argument to TRUE.
Note: you can extend the above functionality to other iterables, such as tuples, setsand others.
For more complex classification tasks, we can add the use of wrench function in tidy () which will act as a key for sorting.
There are two ways to use a key function:
- Using the lambda function as wrench function
- Using custom function like wrench function
Using the lambda function with sorted()
Let’s create a sample list with words:
['Python', 'programming', 'tutorial', 'code']
Now, in this example, we would like to sort the list based on the length of the elements, which means that the words will be sorted from shortest to longest based on the number of characters.
As you can imagine, we will have to use the long() to calculate the length of each element, and using a lambda function we can use it as a key function to sort:
#Create a list of words
words = ['Python', 'programming', 'tutorial', 'code']#Sort the list of words based on length of each word
s_words = sorted(words, key=lambda x: len(x))
#Print sorted list
print(s_words)
and you should get:
['code', 'Python', 'tutorial', 'programming']
Using custom function with sorted()
Let’s reuse the same word list from the previous example:
['Python', 'programming', 'tutorial', 'code']
Now, we’d like to do the same sorting based on the length of each item in the list, but using a custom function to calculate the length of each word.
We can define a simple function to calculate the length of a word and pass it to tidy () as a wrench function:
#Create a list of words
words = ['Python', 'programming', 'tutorial', 'code']#Define a function to calculate length of a word
def calc_len(word):
len_w = len(word)
return len_w
#Sort the list of words based on length of each word
s_words = sorted(words, key=calc_len)
#Print sorted list
print(s_words)
and you should get:
['code', 'Python', 'tutorial', 'programming']
which is the same result as when we use the long() with lambda function as wrench function for tidy ().
Python functionality tidy () The function can be extended to custom objects (as long as we are ordering iterables).
For example, let’s create a custom class Person with two attributes Name Y years:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return repr((self.name, self.age))
This class will create a list of tuples with information about each person:
#Create a list of tuples
persons = [
Person('Mike', 20),
Person('John', 35),
Person('David', 23),
]#Print list of tuples
print(persons)
and you should get:
[('Mike', 20), ('John', 35), ('David', 23)]
As you can see, this is now a list of tuples, which is iterable in Python, and can be sorted using tidy () function.
In this example, we would like to sort the list by years attribute of each person:
#Sort the list of tuples based on age attribute
s_persons = sorted(persons, key=lambda person: person.age)#Print sorted list
print(s_persons)
and you should get:
[('Mike', 20), ('David', 23), ('John', 35)]
In this article we explore how to use Python sorted() function.
Now that you know the basic functionality, you can practice using it with other iterables. Data structures for more complex use cases.
Feel free to leave comments below if you have any questions or have suggestions for some edits and see more of my Python functions tutorials