0
0
Pythonprogramming~5 mins

sorted() function in Python

Choose your learning style9 modes available
Introduction

The sorted() function helps you put items in order, like sorting names alphabetically or numbers from smallest to largest.

When you want to arrange a list of names in alphabetical order.
When you need to sort numbers from lowest to highest.
When you want to organize data before showing it to users.
When you want to sort items without changing the original list.
When you want to sort based on a special rule, like sorting by length of words.
Syntax
Python
sorted(iterable, *, key=None, reverse=False)

iterable can be any group of items like a list, tuple, or string.

key lets you choose a rule for sorting, like sorting by length.

Examples
Sorts numbers from smallest to largest.
Python
sorted([3, 1, 2])
Sorts words in reverse alphabetical order.
Python
sorted(['apple', 'banana', 'cherry'], reverse=True)
Sorts words by their length, shortest first.
Python
sorted(['apple', 'banana', 'cherry'], key=len)
Sorts letters in the word alphabetically.
Python
sorted('hello')
Sample Program

This program shows how sorted() keeps the original list the same and creates a new sorted list. It also shows sorting numbers in reverse order.

Python
fruits = ['banana', 'apple', 'cherry']
sorted_fruits = sorted(fruits)
print('Original list:', fruits)
print('Sorted list:', sorted_fruits)

numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers, reverse=True)
print('Numbers sorted from largest to smallest:', sorted_numbers)
OutputSuccess
Important Notes

sorted() does not change the original list; it makes a new sorted list.

You can sort any iterable, not just lists.

Use reverse=True to sort backwards.

Summary

sorted() arranges items in order and returns a new list.

You can sort by normal order, reverse, or a custom rule with key.

The original data stays the same after sorting.