Join Regular Classroom : Visit ClassroomTech

Python Tuple – sorted() Method

It is a method in tuple that returns a sorted list of the original tuple in ascending order by default. It returns a list.

Syntax:

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

Note: reverse=True will sort the tuple in descending order.

Don’t know what is min method in Python Tuple? Read: Python Tuple – min() Method

Example 1:

# Python program to understand sorted() method in tuple
# www.codewindow.in
s = (2, 9, 7, 9, 33, 45, 52)
x = sorted(s)
print(x)

Output:

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

Explanation:

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

Example 2:

# Python program to understand sorted() method in tuple
# www.codewindow.in
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:

# Python program to understand sorted() method in tuple
# www.codewindow.in
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