I ran the following code in Python:
x = [1, 2, 3, 4, 5, 6]
for a in x:
x[a] = 0
I was expecting it to set every element in the list to 0 but the output I got when I printed the list was:
>>> [0, 0, 3, 0, 5, 0]
Why is this?
CodePudding user response:
The problem is the loop you are using, you need to use for I in range (length of the loop): this outputs [0,0,0,0,0,0].
x = [1, 2, 3, 4, 5, 6]
for i in range(len(x)):
x[i] = 0
print(x)
