13. Modifying each element in a list in a function


#1

Task:

Create a function called double_list that takes a single argument x (which will be a list) and multiplies each element by 2 and returns that list. Use the existing code as a scaffold.

My code:

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

Error:

Oops, try again. double_list([0, 1]) returned [0, 1] instead of [0, 2]

Question:

What's wrong?


#2

First of all you named the function func_1 - but it should be named double_list :grinning:

Take a closer look at the body of your for-loop. What is n_1 and n? What type has x?


#3

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

Return error:

Oops, try again. double_list([0, 1]) resulted in an error: list indices must be integers, not list


#4

you renamed the function - step 1 is done.
but what about my other comments and questions:


#5

What is n_1 and n? What type has x?

I dunno. This excersice is stupid, becouse using thing (range) i dont know yet.
More, in hint was:

You can place the code on lines 3 - 5 inside a function definition. You will need to change the n[i]s in the for loop to x[i]. Make sure to indent properly!

That's what i done. So yes - i dont ■■■■■■■ know what's going on, what's n_1 and n.


#6

I get idea of this site - making stupid unlogical excersices and then make users confused, and get users's money they pay for codecademy PRO account or whatever it's named that includes

Get live, fast support from Codecademy Advisors when you get stuck.
Learn more.

#7

of cousre i will be need help and advice when tasks is ■■■■■■■ ■■■■■■■■-made


#8

Updated code:

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

Now error:

Oops, try again. double_list([0, 1]) returned 2 instead of [0, 2]


#9

well - you introduced n_1 and n in your code, so you should know why and what it is.

you can access the items of a list at a specific position with an index, for example my_list[3] allows access to the forth item, because indices start with 0.

in this exercise you should use the variable i as the index for your list, and the range function will increase this index by 1 in each loop up to the index of the last element. (simplified explanation - you will learn range later)

addition: your last posted code is almost correct - but you return only one item of the list. return the complete list!


#10

Can't get even ■■■■■■■ atom of this. ■■■■ all that.


#11

I don't know ■■■■■■■ WHY but it's should be like that:

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

print double_list(n)

#12

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