Modifying each element in a list in a function why do I need to use x[i]?


I don’t understand in this function why I need to be using x[i] vs. i

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)

Why can’t I just use i?


n = [3, 5, 7]

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


if we want to update an element in a list:

a_list= ['a','b','c']
a_list[2] = 'd'

that is the syntax we use. Using a for loop, its still the same. the i is only a read-only value from the list, any changes made to it won’t persist given the loop re-assigns in the next value of the list in the following iterations. No changes are then made to the actual list


Ok so I think I understand, although what you just said was never spelled out in the exercise.

If I want to change a value in the list it needs to be written as x[1] not just x because when looping through a list “x” is read-only, while x[1] allows us to reassign a value to x[1]?


it must have been spelled out in earlier exercises that updating the list element requires the following syntax:

the_list[index] = "new value"

as long as you understand it now, its fine :slight_smile:


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