12. Printing out a list item by item in a function


#1


https://www.codecademy.com/en/courses/python-beginner-nzzVa/3/1?curriculum_id=4f89dab3d788890003000096

"Your function caused the following error: maximum recursion depth exceeded"

I thought it would print the list item by item.


n = [3, 5, 7]
def print_list(x):
    for i in range(0, len(x)):
        print print_list(n)


#2

no, print_list(n) will call the function, and start again, and again, a sort of infinity loop.

i will now hold the index of the items in the list, as we can see:

 def print_list(x):
    for i in range(0, len(x)):
        print i

so we can use this index to access the items of the list:

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

see i use x here? Not n, you can pass n as argument when calling the function:

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

oh now i see what you did, you placed the function call inside the function, bad idea. now the function argument n will be passed into x (your function argument), this way your function will work for many different lists


#3

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