Can't figure what's wrong with my code


#1

i cant figure our whats wrong with my code:

n = [3, 5, 7]

def double_list(x):
for i in range(0, len(n)):
x[i] = x[i] * 2
return x

print double_list(n)


13/18 list and functions. help?
#2

@bitslayer37642

Call the return outside of the for loop.

n = [3, 5, 7]

# Don't forget to return your new list!
def double_list(x):
    for i in range(0, len(x)):
        x[i] = x[i] * 2
    return x

print double_list(n)

You are doing this because you first tell the code that for every i in list x in the range 0 to the length of the list (len) to multiply its value by two.
Then you return that amount in step 2. If you put the return in a for loop you basically tell the code to first do multiply in step 1A and then to return the amount in step 1B. That's not logical in this exersize.


#3

my code now returned:
[6, 10, 14]
None
isn't that right?
it still gets an error:
Oops, try again. double_list([0, 1]) resulted in an error: list index out of range


#4

your function should work for multiply lists, look at this code:

def double_list(x):
   print x
double_list([1,2,3])
double_list([4,5,6])
double_list([7,8,9])

see how x contains every list. the argument (lists) gets passed to the function parameter (in this case x)

you should loop over x so your function works for multiply lists, instead of one fixed lists.


#5

it finally worked! but i still dont get why it was wrong though I got the same result.


#6

the exercise will validate if your code works correctly by calling your function with different lists, your function could only handle one lists


#7

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