How to return a complete for Loop in a function

Question:

I’m trying to run a For loop in a function but when I call the function only the first value is returned.

I’ve tried ending the loop with a print instead of a return, which gets the correct result (It prints every value in the loop) but means a none is added to the answer as there is now a double print.

PLEASE NOTE: In these examples one could one could just print “value” directly but I want to be able to run through a for loop, to add complexity later.

The function ending in return only prints out the first value of the `For loop“:

def thing():  
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
    return x

print(thing())
# 1 

This function uses print and gives the correct result except with a none added due to the double print.

def thing1():
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
     print(x)

print(thing1())

>>>  OutPut:
1
2
3
4
5
6
7
8
9
10
None

How exactly can I get the second result(the full printed loop of all values) whilst removing the “None”?

Asked By: X-cessive Pupil

||

Answers:

After return is run, the function stops evaluating. If you’d like to return everything in a for loop, return a list of its outputs:

ret_vals = []
for x in value:
    ret_vals.append(x)

return(ret_vals)    

You can print them on new lines like you specified like so:

out = func()
for x in out:
    print(x)
Answered By: Alec

You can use generators to return the sequence.

The generator follows the same syntax as a function,
but instead of writing return, we write yield whenever it needs to return something.

def thing():  
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
    yield x

res = thing()
for i in res:
  print(i, end=' ')

output:
1 2 3 4 5 6 7 8 9 10

Hope you find this helpful !

Answered By: Sneha R