-1
def myarray(num_list):
    for item in num_list:
        return item

def myarray(num_list):
    for item in num_list:
        print (item)

When I run myarray([2,4,6]) the first returns only 2 while the second prints all the items:

2
4
6

Why? What's the difference?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
XYZ123
  • 1
  • 1
    Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – John Kugelman Oct 06 '20 at 16:33
  • SO is not a python tutorial website. If you don't know how to code, first learn how to code then come back here and ask serious questions. Read books and the documentation. Watch tutorials. Do NOT try to learn from SO questions; they should be your last resort. – Alex Mandelias Oct 06 '20 at 16:48

1 Answers1

1

The first statment only returns "2" because the keyword "return" stops the rest of the loop from running.

In the second version you simply print out the content of the list for each position in the list. Thats why the second version shows all 3 numbers.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
FrozenAra
  • 509
  • 2
  • 14