To give you a better idea of how methods (functions for classes, but basically irrelevant because they work the same way) and
return works, let’s take these examples with a few of Python’s built-in datatypes.
First, let’s consider Python’s
str type. (Just a string,
"Hello world!") If we have a variable,
hello = "Hello!", and you wanted to make everything uppercase, you would have to do something like the following:
hello = hello.upper()
Then, take Python’s
list type. Let’s say we have a list,
someList = [1, 2, 3] and we wanted to add a value to the end of the list. This could be done using
Based on my previous post, can you guess which is a
return function and which is a
void function (technically they are methods, but that isn’t important)?
str is a
return function, and
list is the
void function. This is the case because
list is immutable and
str is not, but you will learn more about that later.
The main difference between these two is that
str preforms an operation, and returns the value after said operation is complete. In this case, the
.upper() method is converting the string to uppercase, but it isn’t actually reassigning the string to uppercase. It only returns the uppercase value of that string, which the programmer can reassign to the original variable, or use in some other purpose.
Notice that the
list doesn’t do that. You will only need to call the method and your list is automatically updated with the appended version. That’s because the method actually adds the value directly to the original
list, and it doesn’t
return a value because the list was already updated.
I would highly recommend learning about mutable and immutable datatypes in Python, as this post will make much more sense afterward.