Explanation for the iteration semantic


#1


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

Traceback (most recent call last):
File "python", line 13, in
File "python", line 8, in double_list
IndexError: list index out of range

I expect the "i" in the "for i in x:" loop to take the value of each index of the x list starting from 0 until the last. However, this is not the case. It seems to take a value higher than 2 as my list has 3 elements on it and I get the "index out of range" message.

On the other hand, if I do the exercise with the "for x in range(0, len(x))" syntax the function does work correctly. ¿Can someone advanced explain to me why my "i" doesn´t take the value of each index in my function? I´d appreciate it much, as it is something i thought had grasped correctly in the "foreach" loops in JavaScript and PHP.


n = [3, 5, 7]


# Don't forget to return your new list!

def double_list(x):
    for i in x:
        x[i] *= 2
    return x
        

        
double_list(n)


#2

Print it out and see what it is

Also consider what range(len(something)) returns and how that's used by the for-loop


#3

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