Modifying each element in a list in a function/how the computer reads it?


#1



for this exercise https://www.codecademy.com/en/courses/python-beginner-nzzVa/3/2?curriculum_id=4f89dab3d788890003000096

how does the computer read the for loop. I'm not understanding how this function works? the length of x = 3 that makes the range [0,1,2] so how does x[i] start off with 3 * 2 = 6?


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

#2

    i in range

The range is a list of counting numbers beginning with the first argument and up to but not including the second argument.

[ 0, 1, 2 ] but not `3` (length of x)

The program uses these values as the index in each iteration.

x[0] == 3 so x[0] * 2 == 6
x[1] == 5 so x[1] * 2 == 10
x[2] == 7 so x[2] * 2 == 14

#3

I got that part but what I don't get is this:

n = [3, 5, 7]
def double_list(x):
    for i in range(0, len(x)): so i would be 3,5,7 in range (0,3)
        x[i] = x[i] * 2   so wouldn't it start with x[i] = x[3] * 2 since i starts with 3; how does x[i] start with x[0]?
    return x
print double_list(n)

#4

When i is 0, x[i] is 3. There is no x[3] in the above list.

    index = range (0, 3)
    print (index)    # [ 0, 1, 2 ]
    for k in index:
        x[k] *= 2

#5

okay i get it now thanks for clearing that up for me