Method list.sort() vs function sorted()
The more I program, the more I find myself realizing the why of some of the basics.
You can use either a method or a function to sort or reverse a list in Python. One works in-place, meaning the order of items in the original list is changed. The other works on a copy of the list and returns an ordered version of that copy as a new list.
list.sort()
and list.reverse()
are methods of the list class. They are both verbs, suggesting they take actions on an instance of the list
class. And as methods that are internal to a list, they are understandably “allowed” to change the internal order of list items.
sorted()
and reversed()
are functions external to the list class. They are both adjectives. If a function tampers with the data passed in as an argument, that makes it not a pure function. So in functional programming terms, they are both pure functions.