7

Very new to programming.
Wondering why does this example print all the items in the list, while the second example prints only the first?

def list_function(x):
    for y in x:
        print(y)

n = [4, 5, 7]
list_function(n)

def list_function(x):
    for y in x:
        return y 

n = [4, 5, 7]
print(list_function(n))
user3840170
  • 26,597
  • 4
  • 30
  • 62
Dude
  • 145
  • 1
  • 9

2 Answers2

6

Your first example iterates through each item in x, printing each item to the screen. Your second example begins iterating through each item in x, but then it returns the first one, which ends the execution of the function at that point.

Let's take a closer look at the first example:

def list_function(x):
    for y in x:
        print(y)  # Prints y to the screen, then continues on

n = [4, 5, 7]
list_function(n)

Inside the function, the for loop will begin iterating over x. First y is set to 4, which is printed. Then it's set to 5 and printed, then 7 and printed.

Now take a look at the second example:

def list_function(x):
    for y in x:
        return y  # Returns y, ending the execution of the function

n = [4, 5, 7]
print(list_function(n))

Inside the function, the for loop will begin iterating over x. First y is set to 4, which is then returned. At this point, execution of the function is halted and the value is returned to the caller. y is never set to 5 or 7. The only reason this code still does print something to the screen is because it's called on the line print list_function(n), so the return value will be printed. If you just called it with list_function(n) as in the first example, nothing would be printed to the screen.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
  • Thankyou. I do understand that, what I'm confused about is your second sentence.. why does it only return the first one? – Dude Aug 31 '15 at 13:24
  • @Dude, because `return` returns the value and then _ends execution of the function_, whereas `print` just prints the value. The only reason the second one prints out the value is because you're calling `print` with the return value. – Cyphase Aug 31 '15 at 13:26
  • ah sorry didn't read the word "begins". That makes sense now. Thanks – Dude Aug 31 '15 at 13:27
  • @Dude, sure thing. If this answered your question, you should upvote and accept the answer :). Also upvote other good answers. https://stackoverflow.com/help/someone-answers – Cyphase Aug 31 '15 at 13:37
-1

For functions return terminates the execution, therefore nothing will be executed after return.

In your case the first function will print all the items because there is nothing that breaks the process. However in the second function it will return and end the process.

Semih Yagcioglu
  • 4,011
  • 1
  • 26
  • 43