Printing out a list item by item in a function


#1



It doesn't work. I don't understand why.


n = [3, 5, 7]

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


#2

It doesn't work because in telling it to print_list(n), you're telling it to print the second entity in the n array, as opposed to having a for loop or something similar.

The issue arises from

in that you're telling it to show the second item in the array.

Hope I helped :slight_smile:
If you want/need more help, feel free to ask.


#3

I am only doing what they are asking in the exercise:

  1. Define a function called print_list that has one argument called x.
  2. Inside that function, print out each element one by one. Use the existing code as a scaffold.
  3. Then call your function with the argument n.

Because I would never come up with the scaffold they are giving.

I would like to know what is "i"
and
how does the function know that it has to take the list n written above, if it is not even referring to n?


#4

i is basically how many entities there are in the range you provide.

You're basically saying "For every thing in the range of 0 and however large the given array is, I want it to print a specific array index."

I don't think the instructions are telling you to use 1 for what index needs to be printed. Maybe you should try something that covers every item in the array.

It only knows what you tell it to know. In the function, you're using x as a placeholder. So when you go to call, you need to provide an x. When you do that, every "x" in the function is replaced with what you used instead. By calling print_list(n), you're telling it to use the variable n instead of x.


#5

n = [3, 5, 7]

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

print print_list(n)


#7

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