Python sorted() built-in function

From the Python 3 documentation

Return a new sorted list from the items in iterable.

Introduction

The sorted() function returns a new sorted list from the items in an iterable. It does not modify the original iterable.

You can also use the reverse parameter to sort in descending order.

Examples

Sorting a list of numbers:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 1, 2, 3, 4, 5, 6, 9]

Sorting a list of strings:

words = ["banana", "apple", "cherry"]
sorted_words = sorted(words)
print(sorted_words)  # Output: ['apple', 'banana', 'cherry']

Sorting in reverse order:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [9, 6, 5, 4, 3, 2, 1, 1]

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.