
Why Python's sorted() Is Safer Than list.sort() in Production Systems
Every Python tutorial puts sorted() and list.sort() side by side and says something like: "sort() modifies in place, sorted() returns a new list." That is correct. And for a script that runs once and exits, it is probably enough. But if you write backend services — where request handlers share state, where functions receive lists as arguments, where a cache holds data that multiple parts of the codebase read — this explanation misses the details that cause real incidents. This article covers those details. By the end you will understand exactly what CPython does in memory during each operation, what the GIL actually protects during a sort (and where a popular explanation gets it wrong), and why the mutation behaviour of list.sort() is a consistent source of bugs that are hard to find. The One-Line Difference That Misleads People nums = [ 3 , 1 , 4 , 1 , 5 ] # list.sort() — modifies the list, returns None nums . sort () print ( nums ) # [1, 1, 3, 4, 5] # sorted() — leaves the input alon
Continue reading on Dev.to Tutorial
Opens in a new tab




