Sort Lists

Python allows you to sort lists in ascending or descending order. You can sort a list in place using the sort() method or return a new sorted list using the sorted() function.

Using sort():

Python
fruits = ["banana", "apple", "cherry"]

# Sort the list in ascending order
fruits.sort()
print(fruits)  # Output: ["apple", "banana", "cherry"]

# Sort the list in descending order
fruits.sort(reverse=True)
print(fruits)  # Output: ["cherry", "banana", "apple"]

Using sorted():

The sorted() function returns a new sorted list without modifying the original list:

Python
fruits = ["banana", "apple", "cherry"]

# Get a sorted list
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # Output: ["apple", "banana", "cherry"]

# The original list remains unchanged
print(fruits)  # Output: ["banana", "apple", "cherry"]