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


#1

Hi guys.
I'm having some troubles with my code.
Here is it below:

n = [3, 5, 7]

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

the report i receive is:
Oops, try again. Your function caused the following error: list index out of range

Can someone help me with it?


#2

len(n), n but your function's parameter is x ?


#3

lets say i add another function call:

n = [3, 5, 7]

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

your function should work for both lists, it currently doesn't

the clue to solving this has to do with function parameters and arguments


#4

Thank you, greeetreemee. It worked.
But, I do not understand what I'm doing in it.
See, there is a list called n, with 3 indexes.

So I created a function called "print_list", with an x ‚Äč‚Äčargument.
Okay, I'm good here.

Now start my troubles.

For i in the interval (0, len (x)) - what does he means with "len (x)"?

And "print x[i]"?

Can you explain better for me?


#5

len() is a built in function which can calculate length, in this case the length of list

so now range() will produce a list which happens to matches the indexes of your list x, so then we can use x[i] to retrieve value from list (x) using indexes (i)


#6

I know what are you thinking. You think that You have to loop over n list so you will use len(n) inside the function..
lets understand..

suppose I made a function..

def double(x):
    print (2 * x)

You can see what this function does,It can take any number as argument and print double of it..

like if these are our variable..

a = 3
b = 4
c = 5

and we pass them one by one to our function.

Double(a) #prints 6
Double(b) #prints 8
Double(c) #prints 10

Our `x' variable is just act as placeholder/a variable inside the function ,When we pass our value to function ,then all x is replaced by this value and function does operation i.e. it has to do on value(here function just doubles it)

same way when we create this function(in your post),
we create a general function that can take any list as argument/value and prints its items.

DELETED

(I will delete this code soon)

so when you pass any list of any length,it handles it!


#7

Hmm
I got it now.
Thank you guys!!


#8

Thank you greentreemee.
It was very helpful for me.
I'm a beginer, and Python is my first language. That's why I have some basic questions like these. ^^

see ya


#9

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