Printing out a list item by item in a function


#1



Hi,

What am I doing wrong here please?


n = [3, 5, 7]

def print_list(x):
    for i in range(0, len(x)):
        return x[i]
        
print print_list(n)


#2

a function ends the moment a return keyword is reached

are you sure you not suppose to print x[i]?


#3

Ok I found out.
With my understanding It didn't work as I asked to get only first item from list and close the loop afterwards.
Am I right with this understanding?.

Thank you


#4

You are returning x[i] when you should be printing x[i].

Also, yes. Because you are returning x[i], the for loop only runs once. This is due to the fact that it got a value in its first iteration.


#5

Thanks all for help.


#6

return ends the function, so your function simply ends in the first iteration/run of the loop, the rest of the loop iterations never occur because the function (and thus the loop) has ended


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.