a=[]
a.append(0)
a.append(0)
print(a)
for i in a:
i+=1
print(a)
I think it should print [0,0] [1,1]
but it prints [0,0] [0,0]
.
What is wrong?
When you use for i in a
, in each iteration you're assigning an element of a
to a variable named i
, and when you do an operation on i
, the changes won't be applied to elements of a
. Try:
for i in range(0, len(a)):
a[i] += 1
you are changing the value of i
and that's not changing the elements of the list a
.
if you want to change the value of the elements of that list, you can do:
a=[]
a.append(0)
a.append(0)
print(a)
for index, element in enumerate(a):
element+=1
a[index] = element
print(a)
You need to change the value of each element in a
instead of the value of i
because this is not changing the elements of a
. To change each element on a
you can do:
a = [0,0]
print(a) # [0,0]
for i in range(len(a)):
a[i] += 1
print(a) # [1,1]
or using the function enumerate()
if you want to iterate over the list instead of the range:
a = [0,0]
print(a) # [0,0]
for index, _ in enumerate(a):
a[index] += 1
print(a) # [1,1]