What is sort() and sorted() functions in Python?
Python provides two methods for sorting lists: sort()
(which modifies the list in place) and sorted()
(which returns a new sorted list). Both methods allow sorting in ascending or descending order.
Why to use the sort and sorted functions?
Sorting data is a common requirement for organizing and presenting information. In scenarios like preparing barangay records or lists, sorting helps display information in an accessible way.
Syntax
- list.sort() sorts the list in place.’
- sorted(list) returns a sorted copy without modifying the original.
list.sort(reverse=False) sorted(list, reverse=False)
Example
Let’s say we want to sort the donations for the barangay using the sort and sorted functions.
donations = [1500, 2000, 500, 3000, 1200] # Sort donations in ascending order donations.sort() print("Sorted Donations:", donations) # Output: [500, 1200, 1500, 2000, 3000] # Sort donations in descending order sorted_donations = sorted(donations, reverse=True) print("Descending Sorted Donations:", sorted_donations) # Output: [3000, 2000, 1500, 1200, 500]