Need to show tasks by urgency rather than creation order? Sorting rearranges their list into the order you choose. Python’s list.sort() changes the original list in place and returns None; by default, it sorts in ascending order. Use reverse=True for descending order. section 3.2 section 3.2.1
For numbers or strings, the default comparisons may be enough. Dictionaries cannot be compared that way, so give sort() a key function. It receives one item and returns the value used to place that item in order; the list still contains the original items. section 3.2 section 3.2.2 section 3.2.3
Put the most urgent task first
tasks = [{'title': 'Laundry', 'urgency': 3}, {'title': 'Homework', 'urgency': 5}, {'title': 'Museum', 'urgency': 2}] def urgency(task): return task['urgency'] tasks.sort(key=urgency, reverse=True) print([task['title'] for task in tasks]) # ['Homework', 'Laundry', 'Museum'] The key selects each task’s urgency; reverse=True puts the highest value first. section 3.2 section 3.2.3
Choose the sorting operation that fits the job:
- Use list.sort() when changing the existing list is intended. Do not chain another method onto its result: that result is None. section 3.2.1 section 6.2.1
- Use sorted() when you need a new sorted list, including when the input is another iterable such as a tuple, set, or dictionary. section 3.2.4 section 5.3.6
- Use a one-argument key function for a custom order. A short lambda can express a small key operation; len can serve as a key when length determines rank. section 3.2.3 section 3.2.5
A key can also make otherwise incompatible items comparable: key=str sorts mixed items by their string forms while retaining the original objects. Choose that rule only when string order is the order you actually want. section 3.2.1 section 3.2.2

















