Python sorted() Function: Complete Guide with Syntax, Examples & Use Cases

Introduction: Python sorted() Function

When working with Python, there are many situations where data needs to be arranged in a specific order. Whether you’re organizing names, sorting numbers, or displaying records alphabetically, keeping data in order makes it easier to read, search, and process.

Without a built-in sorting function, you would need to write your own sorting logic or modify the original data manually, making programs longer and more difficult to maintain.

This is where the Python sorted() Function becomes useful.

What it is: The sorted() function is a built-in Python function that returns a new sorted list from the items of an iterable. By default, it sorts the items in ascending order, but it also supports custom sorting using optional parameters.

The Python sorted() Function provides a simple and flexible way to sort data without modifying the original iterable.

A quick example makes it easier to understand the function.

You can also explore where it is commonly used through its use cases in Python.

Now let’s understand its syntax, parameters, and return value before exploring practical examples.

💡 Tip: The sorted() function is one of several functions used to work with collections. Explore the complete Built-in Functions Learning Guide for more related functions.

Syntax, Parameters, Return Value and Examples: Python sorted() Function

The following section explains the syntax, parameters, return value, and a quick example of the Python sorted() Function.

Syntax

sorted(iterable, *, key=None, reverse=False)

Parameters

Parameter Description
iterable The iterable whose items are to be sorted, such as a list, tuple, string, dictionary, or set.
key (optional) A function that specifies the value to use for sorting each item.
reverse (optional) If True, the items are sorted in descending order. The default value is False.

Return Value

Return Value Description
list Returns a new list containing the sorted items from the specified iterable.

Quick Example

The following example sorts a list of numbers using the sorted() function.

numbers = [40, 10, 30, 20]

print(sorted(numbers))

# Output:
[10, 20, 30, 40]

The sorted() function returns a new list with the items arranged in ascending order. The original list remains unchanged.

How the Python sorted() Function Works

  • The sorted() function accepts an iterable as its first argument.
  • By default, it sorts the items in ascending order.
  • The optional key parameter specifies the value used for sorting.
  • The optional reverse parameter sorts the items in descending order when set to True.
  • The function always returns a new sorted list.
  • The original iterable is not modified.

Examples: Python sorted() Function

The following examples show how the Python sorted() Function works in different programming scenarios.

Example 1: Sorting a List of Numbers

numbers = [40, 10, 30, 20]

print(sorted(numbers))


# Output:
[10, 20, 30, 40]

Explanation: The sorted() function returns a new list with the numbers arranged in ascending order. The original list remains unchanged.

Example 2: Sorting in Descending Order

numbers = [40, 10, 30, 20]

print(sorted(numbers, reverse=True))


# Output:
[40, 30, 20, 10]

Explanation: Setting reverse=True sorts the items in descending order.

Example 3: Sorting a Tuple

marks = (75, 91, 82, 68)

print(sorted(marks))


# Output:
[68, 75, 82, 91]

Explanation: Although the input is a tuple, the sorted() function returns a new sorted list.

Example 4: Sorting Strings Alphabetically

names = ["Charlie", "Alice", "Bob"]

print(sorted(names))


# Output:
['Alice', 'Bob', 'Charlie']

Explanation: By default, strings are sorted in alphabetical order.

Example 5: Sorting by String Length

words = ["banana", "kiwi", "apple", "fig"]

print(sorted(words, key=len))


# Output:
['fig', 'kiwi', 'apple', 'banana']

Explanation: The key parameter specifies that the words should be sorted according to their length instead of alphabetical order.

Example 6: Sorting User Input

numbers = input("Enter numbers separated by spaces: ").split()

numbers = [int(num) for num in numbers]

print(sorted(numbers))


# Sample Output:
Enter numbers separated by spaces: 25 8 14 30
[8, 14, 25, 30]

Explanation: The user enters multiple numbers, which are converted into integers before being sorted in ascending order.

Use Cases: When to use the sorted() Function

Below are some common situations where the Python sorted() Function becomes useful:

  • Sorting numbers in ascending or descending order.
  • Arranging names and text alphabetically.
  • Sorting lists, tuples, sets, strings, and other iterables.
  • Displaying data in an organized order without modifying the original iterable.
  • Sorting data using custom criteria with the key parameter.
  • Preparing data for searching, reporting, and analysis.

Key Takeaways: sorted() Function

Before wrapping up, here are the key points to remember about the Python sorted() Function:

  • The sorted() function returns a new sorted list from the items of an iterable.
  • By default, the items are sorted in ascending order.
  • The reverse parameter sorts the items in descending order.
  • The key parameter allows custom sorting based on a specified criterion.
  • The original iterable is not modified.
  • It works with lists, tuples, strings, sets, dictionaries, and other iterables.

In short, the Python sorted() Function provides a simple and flexible way to sort data while preserving the original iterable, making Python programs easier to read and maintain.

Leave a Comment

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

Scroll to Top