Modifying each element in a list in a function


#1



https://www.codecademy.com/courses/python-beginner-nzzVa/3/2?curriculum_id=4f89dab3d788890003000096#

"Oops, try again. double_list([0, 1]) resulted in an error: list index out of range"

It is printing the values I would expect, 6,10,14. I am new to this and am still struggling to come to terms with the basics for instance a totally off topic question why can a for loop take anything as an argument, for instance "i" in the below part could be item etc, this puzzles me a little. Any help would be great, thanks.


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)


#2

this line:

for i in range(0, len(n)):

this should be len(x), why? Because the exercises tries different lists to test if your code is correct. You don't want to use the length of the list passed into the function, not of the one you defined on line 1


#3

A post was split to a new topic: 12. I still don't get it


#4

So first off let me explaini why the editor is telling you that the list index is out of range... As you already learned, the indexes for lists start from 0. So in your list you have the following:
n = [3, 5, 7]
that means that internally the list knows the following indexes:
at index 0 the list knows it has the value 3
at index 1 the list knows it has the value 5
at index 2 the list knows it has the value 7

Having said all the above that means your expression has the following meaning:
1. i is a number in the range of 0 to 3 as len(n)=3
2. when you are trying to perform operations with the elements of the list you access them using via their index:
x[0]=3
x[1]=5
x[2]=7
x[3]=unknown to the list as you only have 3 elements in the list you declared which results in the "list index out of range"

Now to your second question... For lack of better wording the python interpreter doesn't care how you name that variable, it just knows that it will store in it values that range from 0 to 3 (as you declared it) so as you put it can be named john, pizza, element, trees, whatever and python will be content knowing to what variables it will dish out values.


#5

Thanks very much I understand now!


#6

Thank you for this reply it has been very helpful and for replying to my second question!