0
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?

martineau
  • 119,623
  • 25
  • 170
  • 301
dlllllyan
  • 5
  • 2

3 Answers3

1

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
Sajad
  • 492
  • 2
  • 10
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)
fayez
  • 370
  • 1
  • 5
1

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]
Raz K
  • 167
  • 8