Python Tips - Sorted

Python Tips - Sorted

Python sorted():

A Guide to Sorting Lists and Other Iterables

In Python, the sorted() function is a powerful tool for sorting lists, tuples, and other iterable data structures. This built-in function returns a new, sorted list from the elements of the original iterable, leaving the original unchanged. It can also be used to sort dictionaries, by sorting their keys, values, or both.

Here's a simple example of how sorted() can be used to sort a list of numbers:

No alt text provided for this image

Output:

[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]        

As we can see, the sorted() function returns a new list with the elements of numbers sorted in ascending order. By default, sorted() sorts elements in ascending order, but we can specify a different order by using the reverse parameter. For example, to sort numbers in descending order, we can do the following:

No alt text provided for this image

Output:

[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]        

In addition to sorting lists, sorted() can also be used to sort other iterable data structures, such as tuples and dictionaries. When sorting a tuple, sorted() returns a new list with the elements of the tuple sorted. When sorting a dictionary, sorted() returns a new list with the keys or values of the dictionary sorted. For example, to sort a dictionary by its keys, we can do the following:

No alt text provided for this image

Output:

['age', 'city', 'name']        

To sort a dictionary by its values, we can use the key parameter of sorted() to specify a function that returns the value to sort on. For example, to sort person by its values, we can do the following:

No alt text provided for this image

Output:

['age', 'name', 'city']        

Conclusion: the sorted() function is a valuable tool for sorting lists, tuples, and other iterable data structures in Python. Whether we're sorting numbers, strings, or dictionaries, sorted() provides an easy-to-use and efficient way to sort our data. So next time you need to sort some data in Python, remember the sorted() function and make your code even better!

#pythonlearning #python #pythoncoding #pythonprogramming #pythondeveloper

要查看或添加评论,请登录

Hugo Tota的更多文章

社区洞察

其他会员也浏览了