A report needs a sorted display but the original input order must be retained for auditing.
What You Need to Understand
list.sort() changes the original list and returns None; sorted() returns a new list from any sortable iterable. Both support key= and reverse= and both are stable.
When to Use It
A report needs a sorted display but the original input order must be retained for auditing.
Step-by-Step Python Example
scores = [90, 75, 88]
report_order = sorted(scores)
print(report_order)
print(scores)
scores.sort()
print(scores)
How the Example Works
The first operation creates a separate result. The second operation modifies the original object.
Example Output
[75, 88, 90]
[90, 75, 88]
[75, 88, 90]
list
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print(type(sorted((3, 1, 2))).__name__)
Important Behavior and Edge Cases
Writing scores = scores.sort() loses the list reference by assigning None. Use sorted() when you need the original unchanged.
Try It Yourself
Sort a tuple with sorted() and inspect the type returned.
Common Beginner Mistakes
- Writing
scores = scores.sort()loses the list reference by assigningNone. Usesorted()when you need the original unchanged. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
list.sort()changes the original list and returnsNone;sorted()returns a new list from any sortable iterable.- The first operation creates a separate result.
- Writing
scores = scores.sort()loses the list reference by assigningNone.