Sorted() Function in Python

In Python, the sorted function is used to sort the elements of an iterable object, such as a list, string, or tuple.

sorted(x)

The argument x is the input iterable object. It can be a list of numbers or values, a tuple, or even a string of characters.

The sorted function arranges the elements in ascending order and returns the sorted result.

Note: To sort in descending order, you should use the reversed function.

A Practical Example

Let's assign an alphanumeric value to a string variable.

string = "ncefgzohbilvpaqrstudm"

Then, use the sorted function to sort the string.

sorted(string)

The function returns the following result:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'z']

The characters in the string are sorted in ascending order according to their ASCII/Unicode code, and presented as a list.

And that's it!

 

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Sorting in Python