Education

Reasons Why You Should Always Use sorted() in Python

A global and popular language, python has gained attention worldwide. It is the most commonly used programming language in the world that is comprehensively used in the industrial as well as academic domains. People use it for scientific computation, data, engineering purposes, web development, and much more. But why python?

Python is one of the most flexible languages out there. It is the most attractive feature and it is easy to function and can give you more than one implemented work. As a data analyst or a data scientist, we are sure you know how much python is helpful. As experienced workers, we know the value of sorted in python.

Here, we are going to quote an example that can help you understand it.

>>> # sort a list using sort()

>>> names0 = [‘Richard’, ‘Danny’, ‘Steve’, ‘John’]

>>> names0.sort()

>>> names0

[‘Steve’, ‘Richard’, ‘Donny’, ‘Danny’]

>>> 

>>> # sort a list using sorted()

>>> names1 = [‘Richard’, ‘Danny’, ‘Steve’, ‘Donny’]

>>> sorted(names1)

[‘Steve’, ‘Richard’, ‘Donny’, ‘Danny’]

As you can see in the example we created multiple lists of names. The names0 and names1. Here we used a special quote called sort () and sorted ().

Both of these codes were helpful to separate the two functions. The list was also obtained in the same order as we thought it would after the function.

All those sort and sorted are similar as they can sort the functions and allocate them differently but people usually opt to use sorted instead of sort. There is the main reason behind it and we are here to decode the same.

The complexity of python is enormous. People are confused and not able to decipher the fundamentals. Professionals can get confused and or not be able to know which suits them better. With the right experience and good fundamental knowledge about the language, you will be able to retrieve the best option.

Here we will explore some of the reasons why sorted is more useful than sort.

It’s Compatible With Iterables

We know the value of iterables and how important it is to get compatible with the same. Sorted () is one of the functions that is flexible. It can interact and support any iterables. The sort () although works exclusively with the lists. Iterables are python objects that are also called iterated in iterations. Common examples include tuples, lists, dictionaries, and sets.

Here we are going to compare the compatible data types in the sorted () and sort (). Before we move along, one should know that we both have two different functions and there is a very subtle difference between the two. Sort can take iterable as an argument whereas the sort can function using dot notation.

Check this out-

>>> # sort a tuple

>>> _ = (3, 5, 4).sort()

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

AttributeError: ‘tuple’ object has no attribute ‘sort’

>>> _ = sorted((3, 5, 4))

>>> 

>>> # sort a dictionary

>>> _ = {2: ‘two’, 0: ‘zero’, 1: ‘one’}.sort()

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

AttributeError: ‘dict’ object has no attribute ‘sort’

>>> _ = sorted({2: ‘two’, 0: ‘zero’, 1: ‘one’})

>>> 

>>> # sort a set

>>> _ = set([2, 3, 4]).sort()

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

AttributeError: ‘set’ object has no attribute ‘sort’

>>> _ = sorted(set([2, 3, 4]))

Dictionaries, sets, and Tuples cannot call sort functions. It is not a collection of objects and is only available for the list. But they can be sorted with the sorted () function making it suitable for the same.

It’s Convenient on Lists

When you sort the iterable in order, you can also return the list objects in the sorted function (). This feature enables the user to create lists conveniently. It may implicitly return none at times. You can consider the following example where a dictionary is named sales_dict. This dictionary has the sales record and we have to create a list sorting the same in descending order.

>>> # records of sales in a dictionary

>>> sales_dict = {‘Spring’: 1000, ‘Summer’: 950, ‘Fall’: 1030, ‘Winter’: 1200}

>>> 

>>> # create a list object of sales records

>>> sales_list0 = sorted(sales_dict.items(), key=lambda x: x[1], reverse=True)

>>> sales_list0

[(‘Winter’, 1200), (‘Fall’, 1030), (‘Spring’, 1000), (‘Summer’, 950)]

>>> 

>>> sales_list1 = list(sales_dict.items())

>>> sales_list1.sort(key=lambda x: x[1], reverse=True)

>>> sales_list1

[(‘Winter’, 1200), (‘Fall’, 1030), (‘Spring’, 1000), (‘Summer’, 950)]

Here the user just had to use a sorted () function to get the result.

You can also not combine the two lines using dot notation. Let’s consider this example-

>>> # combine the two lines

>>> sales_list2 = list(sales_dict.items()).sort(key=lambda x: x[1], reverse=True)

>>> sales_list2

>>> type(sales_list2)

<class ‘NoneType’>

>>> print(sales_list2)

None

Here you will get a non-value because of the sort () function. This proves that the functional value of return in sort is none.

It can be Integrated With Iteration

After we have discovered that this sorted () function is used to create a new list and can return it while the sort () function will give none, what is the difference?

Consider a scenario where there are iterables with NoneType objects. Take an example of two dictionaries being distributed that have the scores for the third and fourth semesters. You have to generate a report Card and summarise the result of students. You also have to sort the performances and the names.

>>> # test results for the third semester

>>> results1 = {‘John’: 95, ‘Danny’: 80, ‘Zack’: 98}

>>> 

>>> # test results for the fourth semester

>>> results2 = {‘Danny’: 84, ‘Zack’: 95, ‘John’: 88}

>>> 

>>> # generate the report card

>>> for name, score in sorted(results2.items()):

… print(f'{name} | Spring: {results1[name]} | Fall: {score}’)

Danny | Spring: 80 | Fall: 84

John | Spring: 95 | Fall: 88

Zack | Spring: 98 | Fall: 95

This can be sorted by the sorted () function. It can integrate the result in a for-loop. If we had used the sort function in the same, the result would have been as follows-

>>> for name, score in list(results2.items()).sort():

… print(f'{name} | Spring: {results1[name]} | Fall: {score}’)

Traceback (most recent call last):

  File “<stdin>”, line 1, in <module>

TypeError: ‘NoneType’ object is not iterable

Conclusion

Now, we came to know about the uses and benefits of the sorted function in python. If we only deal with the list of checks you may use a sort () function but will not get the returns list. There also you have to use the sort function as it offers more benefits. It is more efficient and can work on large and comprehensive lists. We hope this helped!

Read More: 7 Mistakes to Avoid When Hiring a Python Developer

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button