Python sorted function | Sort string, list, tuple, dictionary

Python sorted() function is used to sort string, list, tuple, dictionary, etc and it returns a list with the elements in a sorted manner, without modifying the original sequence.

Syntax

Parameter Values

sorted() method takes a of three parameters:

  • iterable – A sequence or collection or any other iterator.
  • reverse (Optional) – If True, the sorted list is reversed (descending order). Defaults is False will sort Ascending order.
  • key (Optional) – A Function to execute to decide the order. Default is None

Python sorted function Examples

We will see the example of sorting with the deferent type of sequence (string, tuple, list) or collection (set, dictionary, frozen set).

Sort the list of Number and String

Output:

[1, 2, 3, 4]
[‘A’, ‘BB’, ‘CCC’, ‘DDDD’]

How to sort List in ascending order

Use sorted(List, reverse=True) for ascending (reverse) order.

Output: [‘DDDD’, ‘CCC’, ‘BB’, ‘A’]

Sort String using sorted() fun

Output:

[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]

Tuple Elements sorting example Using sorted() Method

Output:

[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

Python sorted dictionary

Output:

[‘e’, ‘q’, ‘r’, ‘t’, ‘w’, ‘y’]

Do comment if you have any doubts and suggestion on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.