How do I sort a list

Sorting a list in Python can be accomplished using the built-in `sort()` method or the `sorted()` function. Both can arrange elements in ascending or descending order based on your preference.

sort, sorted, python, list, ascending, descending

This guide demonstrates how to efficiently sort a list in Python, providing examples for both in-place sorting and returning a new sorted list.


# Example of sorting a list in Python

# Using the sort() method (in-place sorting)
numbers = [5, 3, 8, 1, 2]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 5, 8]

# Using the sorted() function (returns a new sorted list)
numbers = [5, 3, 8, 1, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 3, 5, 8]
    

sort sorted python list ascending descending