Why does a variable needs to be declared to use a method that returns a value?

Hi guys,

I am having some trouble understanding why a variable needs to be declared to use a method that returns a value.

In the exercise I’m currently working on (https://www.codecademy.com/courses/learn-python-3/lessons/use-python-list/exercises/count), it says ‘Notice that since .count() returns a value, we must assign it to a variable to use it.’

The example it provides is;

letters = ["m", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]
num_i = letters.count("i")
print(num_i)
# Output is 4

However, I seem to be able to achieve the same result without declaring a variable;

letters = ["m", "i", "s", "s", "i", "s", "s", "i", "p", "p", "i"]
print(letters.count("i"))
# Output is 4

Please could someone explain this for me? Is it best practice to declare any use of a method as a variable, for some reason that hasn’t been explained in the course yet?

Thanks for your help,
Tom

2 Likes

The assignment isn’t strictly necessary, the bit about it returning a value is the important part. I think this wording may have been used to separate it from some of the list methods that may have already been introduced such as .sort() and .append() which operate in-place and only ever return the None object.

So no, you don’t need to assign it. As you have done this could simply be an expression to evaluate which is passed as an argument to a further function (or part of a logical comparison etc. etc.).

Please see How do I format code in my posts? for posting code to the forums in future as it’s much much easier for others to read, cheers :+1:.

3 Likes

Thank you very much for the explanation :slight_smile: