In Python, you can sort lists using the built-in sort()
method or the sorted()
function. Both methods sort lists in ascending order by default, but you can also specify a custom sorting order.
The sort()
method sorts the list in place, meaning that it modifies the original list.
# Example of using sort()
my_list = [5, 2, 9, 1, 5, 6]
my_list.sort()
print(my_list) # Output: [1, 2, 5, 5, 6, 9]
The sorted()
function returns a new sorted list from the elements of any iterable.
# Example of using sorted()
my_list = [5, 2, 9, 1, 5, 6]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [1, 2, 5, 5, 6, 9]
You can sort lists in descending order by setting the reverse
parameter to True
.
# Example of sorting in descending order
my_list = [5, 2, 9, 1, 5, 6]
my_list.sort(reverse=True)
print(my_list) # Output: [9, 6, 5, 5, 2, 1]
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?