Using the `sorted()` Method

tags: #python/documentation/data_structures/lists/methods

The sorted() function in Python is used to create a new sorted list from the elements of any iterable, not just lists. Unlike the list.sort() method, sorted() returns a new list and does not modify the original iterable in place.

Can the function be used for other objects?

Yes - the sorted() function in Python used to any other iterable object.

General Syntax

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

Example

# Example list of numbers
numbers = [4, 2, 8, 1, 5]

# Create a new sorted list
sorted_numbers = sorted(numbers)

print(sorted_numbers)
# Output: [1, 2, 4, 5, 8]

# Original list is unchanged
print(numbers)
[4, 2, 8, 1, 5]
Powered by Forestry.md