A list of product names should be alphabetized in place.
What You Need to Understand
list.sort(key=None, reverse=False) orders a list in place using a stable sorting algorithm. It returns None and can sort by a derived key.
When to Use It
A list of product names should be alphabetized in place.
Step-by-Step Python Example
products = ["pear", "Apple", "banana"]
products.sort(key=str.casefold)
print(products)
products.sort(key=len, reverse=True)
print(products)
How the Example Works
The first sort ignores ordinary letter-case differences. The second sorts by string length, preserving relative order of equal-length values.
Example Output
['Apple', 'banana', 'pear']
['banana', 'Apple', 'pear']
[7, 2, 1]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
values = [2, 7, 1]
values.sort(reverse=True)
print(values)
Important Behavior and Edge Cases
Do not overwrite the list with the return value. Sorting heterogeneous objects without a common key can raise TypeError.
Try It Yourself
Sort a list of integers descending without creating a new list.
Common Beginner Mistakes
- Do not overwrite the list with the return value. Sorting heterogeneous objects without a common key can raise
TypeError. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
list.sort(key=None, reverse=False)orders a list in place using a stable sorting algorithm.- The first sort ignores ordinary letter-case differences.
- Do not overwrite the list with the return value.