In Python, lists are mutable sequences that can be sorted in-place or used to create new sorted lists. You can sort strings, numbers, and even complex objects using built-in tools like list.sort() and sorted(), along with powerful options such as reverse and key.
list.sort() sorts a list in-place (modifies the original list).sorted() returns a new sorted list, leaving the original unchanged.reverse=True to sort in descending order.key parameter to define custom sorting logic.The simplest way to sort a list is to call sort() on it. This changes the list itself and arranges the items in ascending order.
my_list.sort()
To sort the list in descending order, pass reverse=True to sort() or sorted().
my_list.sort(reverse=True)
Numeric lists are sorted from the smallest to the largest value by default.
The key parameter takes a function that returns a value to sort by. This allows advanced, custom sorting rules.
list.sort() modifies the original list and returns None.sorted(iterable) returns a new list and does not change the original.You can sort a list of strings alphabetically using sort().
fruits = ["orange", "apple", "banana", "cherry"]
fruits.sort()
print(fruits)
Use the reverse=True argument to sort in descending order.
fruits = ["orange", "apple", "banana", "cherry"]
fruits.sort(reverse=True)
print(fruits)
Numeric lists can be sorted just as easily, from smallest to largest.
numbers = [100, 50, 65, 82, 23]
numbers.sort()
print(numbers)
Use a key function to define a custom rule. In this example, numbers are sorted by how close they are to 50.
numbers = [100, 50, 65, 82, 23]
numbers.sort(key=lambda x: abs(x - 50))
print(numbers)
sorted() creates a new sorted list, without changing the original.
numbers = [3, 1, 4, 2]
print(sorted(numbers)) # new sorted list
print(numbers) # original list unchanged
fruits.sort(), the output will be: ['apple', 'banana', 'cherry', 'orange'] (alphabetical order).fruits.sort(reverse=True), the output becomes: ['orange', 'cherry', 'banana', 'apple'] (reverse alphabetical).numbers = [100, 50, 65, 82, 23], after numbers.sort() you get: [23, 50, 65, 82, 100].key=lambda x: abs(x - 50), the list is ordered by distance from 50 (closest to farthest).sorted(numbers), you see a sorted copy, while numbers itself remains unchanged.sort() when you don’t need the original order of the list.sorted() when you want to keep the original list unchanged.key functions; complex logic can reduce clarity.key=len parameter.reverse=True.sorted() to create a new sorted list while keeping the original intact, then print both lists.key=lambda x: x % 3).