Skip to content

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

  • by

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

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

Parameter Values

The sorted() method takes an 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 different types of sequence (string, tuple, list) or collection (set, dictionary, frozen set).

Sort the list of Number and String

number_list = [1, 3, 2, 4]

print(sorted(number_list))

str_list = ["BB", "A", "DDDD", "CCC"]

print(sorted(str_list))

Output:

Python sorted function Sort the list of Number String

How to sort List in ascending order

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

str_list = ["BB", "A", "DDDD", "CCC"]

print(sorted(str_list, reverse=True))

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

Sort String using sorted() fun

 # string
py_string = 'Python'
print(sorted(py_string))

Output:

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

Tuple Elements sorting example Using sorted() Method

# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))

Output:

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

Python sorted dictionary

# Dictionary 
x = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6} 
print (sorted(x)) 

Output:

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

Do comment if you have any doubts and suggestions 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

Your email address will not be published. Required fields are marked *