Different output using return or print()

Hello.

I came across this problem when trying other things.
When I wanted to use this code (see below) to
This one gives me the whole content of the list (alphabet)

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # .....

def first():
     for letter in alphabet:
         print(letter)

first()

output:
a
b
c
d
e
f
g
h
i
j

But this one just gives me the first item in the list

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] # .....

def first():
     for letter in alphabet:
         return letter

print(first())

output: a

I thought I would get the whole of the contents in both cases.
Did I miss a fundamental thing here?
I am a little bit afraid I should know this by now. Then I will be ashamed of my self.
But it is better to reveal that and learn the lesson properly :slight_smile:

Easy, what happens when you do a return?

def first():
   for letter in alphabet:
       for some in somother:
            for another in another:
                return "GOODBYE"!

Even if I was 4 levels down inside a for-loop inside a for-loop inside a for-loop inside a function, when I do return, that function ends and it exits out. You only get the first element because you return right away, so it exits out and done.

Now, the question is, what were you trying to do that made you do return, and why did you think return would do what print does? To help formulate the reply, this is what I think they do:

print – Takes a string of characters and prints them to the standard output device (the screen usually).
return – Pushes a return value onto the stack and then immediately exits the function by jumping to where the function was called. At that point the python program continues where the function was called, and uses the return value as the value of an assignment.

1 Like

Thanks a lot for the explanation.
I will immediately do a lot of exercises on this as soon as I can tonight.
That’s the best way to keep the knowledge inside the head :slight_smile: