I’m confused by the idea that “Methods only generate an altered copy of the original.” In the below example, it seems that “x” IS changed…
x=[12,3,32]
x.sort(reverse=True)
print(x)
out: [32, 12, 3]
Or, the idea of “making a copy, not altering the orignal” just simply can’t be made explicit (e.g. through “print”)
Thanks a lot!
You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility
When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!
If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer!
In x.sort(reverse=True), the .sort is not a “function taking an argument” so much as a method belonging to an object. It’s a good distinction to make.
Objects consist of state and methods that use that state. An object’s methods can mutate the object’s state, as that may be the reason they belong to the object. Think setters.
If I pass an object to a function, I’d rather the function not try to mutate anything, as that would be unexpected. Only that objects methods should mutate it. See principle of least astonishment.
The .sort() method modifies the list in place. It does not make a copy of it.
To build on what @baavgai said…
Methods are part of a class, they are functions that are created inside a class. To execute methods, you need to use the object or class name and the dot operator.
In your example you use .sort() which is a built in method of the list class. The .sort() method will only work with lists. (which is why if you try to use it w/something else, it will throw an error.) .sorted() is different, in that it will work with any iterable. .sorted() also provides you with a new list if you don’t need the original.
The list class has a number of built-in methods. You can see them here.
Methods are dependent on classes, functions are independent of classes. (I assume you’ve not yet gotten to the portion on classes).
All methods are functions, but not all functions are methods.