sorted() Function in Python

Python sorted() Function

The sorted() function in Python is used to sort elements in an iterable (e.g., lists, tuples, strings) in ascending order and return a new list with the sorted elements. It does not modify the original iterable, but instead, it creates a new sorted list.

The general syntax of the sorted() function is as follows:

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

Parameters:

  • iterable: The iterable (list, tuple, string, etc.) that you want to sort.
  • key (optional): A function that specifies a custom sorting order. It takes an element as input and returns a value based on which the sorting is performed. By default, None, which means that the default natural sorting order will be used.
  • reverse (optional): A boolean value that determines whether the sorting should be in ascending (False, default) or descending (True) order.

Here's an example of how to use the sorted() function:

# Sorting a list of integers in ascending order
numbers = [5, 2, 8, 1, 9, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 3, 5, 8, 9]

# Sorting a list of strings in descending order
fruits = ['apple', 'orange', 'banana', 'grape']
sorted_fruits = sorted(fruits, reverse=True)
print(sorted_fruits)  # Output: ['orange', 'grape', 'banana', 'apple']

# Sorting a list of tuples based on a custom key
people = [('John', 25), ('Alice', 19), ('Bob', 32), ('Emily', 22)]
sorted_people = sorted(people, key=lambda x: x[1])
print(sorted_people)  # Output: [('Alice', 19), ('Emily', 22), ('John', 25), ('Bob', 32)]

In the example above, we sorted a list of integers in ascending order, a list of strings in descending order, and a list of tuples based on the second element of each tuple in ascending order. Note that the original lists remained unchanged, and the sorted() function returned new sorted lists.