-3

This code:

i = 0
list = [ i , i+1 , i+2 ]

print(list)

list.append(i+3)
for x in range(0,3):
    i += 1
  
    print(list)

return the following output:

[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3]

I also tried this code, but the result was the same:

i = 0
list = [ i , i+1 , i+2 ]

print(list)

list.append(i+3)
for x in range(0,3):
    i += x
  
    print(list)

and I wanted that it returned this output

[0,1,2]
[0,1,2,3]
[1,2,3,4]
[2,3,4,5]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Note that your list contains `int` objects, not formulas. You can append new value and remove one. Or you can use `collections.deque` with fixed length. As a side note - don't use `list` as name. – buran Jun 29 '22 at 08:02
  • Hey Joao, it's not really clear what's the problem you want to solve here. – jon doe Jun 29 '22 at 08:02
  • Calculated values in the list don't retroactively change… – deceze Jun 29 '22 at 08:04
  • You would need to define a custom class `MyInteger` which is mutable under some circumstances but which also returns a new `MyInteger` instance under different circumstances. You need very special handling of `__add__` and `__iadd__`. – luk2302 Jun 29 '22 at 08:04
  • integers are immutable objects. That means that when you do `i += x` which is equivalent to `i = i + x`, the `i` on the left is a new object, not the same one to the right. So the `i` that was saved in the list will not change – Tomerikoo Jun 29 '22 at 08:06

1 Answers1

0

Are you trying to increment each element?

for x in range(3):
    list=[j+1 for j in list]
    print(list)

Output:

[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
Ash Nazg
  • 514
  • 3
  • 6
  • 14