sorted() method in Python List

It is a method in list that returns a sorted list of the original list in ascending order by default. It returns a new list. It doesn’t modifies the original list.

Syntax:
sorted(iterable, key, reverse=True/Flase)

reverse=True will sort the list in descending order. But keep in mind that we can not sort a list that contains both string values and numbers as well using this method.

Example:

s=[2, 9, 7, 9, 33, 45, 52]
x=sorted(s)
print(x)

Output:
[2, 7, 9, 9, 33, 45, 52]

Explanation:
Here the elements are in sorted order (ascending). It returned a list x which is sorted.

Example 2:

s=["Name", "Codewindow", "India"]
x=sorted(s)
print(x)

Output:
[‘Codewindow’, ‘India’, ‘Name’]

Explanation:
Here it returned a list x in sorted (ascending) order alphabetically according to their ASCII value of the first character of that element.

Example 3:

s=[2, 9, 7, 9, 1, 45, 8]
x=sorted(s, reverse=True)
print(x)

Output:
[45, 9, 9, 8, 7, 2, 1]

Explanation:
Here the elements are in sorted order but reversed (descending). It returned a list which is sorted in descending order.


You Missed

Also checkout