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


#1

EDIT: Nevermind! I changed "for i in range(0, len(n)):" to "for i in range(0, len(x)):" and it worked.

n = [3, 5, 7]

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

print_list(n)

Returns this:

3
5
7
None

And I get an error saying "Oops, try again. Your function caused the following error: list index out of range"

But that's wrong - it should work.

$ cat temp
n = [3, 5, 7]

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

Returns this:

$ python temp
3
5
7

#2

do you also understand why this change works? with x you iterate over the global list you created, where as you use n you iterate over the function parameter, so any list you supply as argument at function call


#3

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