0

I know if I do

x = 1

and then

x += 1

the result is

x=2

And equally

x = x + 1

the result is also

x = 2

so why when iterating over a list is not the same?

For example:

lst = [[1,3,3],[2,2,2],[3,2]]
for i in lst:
  if len(i)!=3:
    i = i +  [0]*1

print(lst)

The result is:

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

And if we use this code:

lst = [[1,3,3],[2,2,2],[3,2]]
for i in lst:
  if len(i)!=3:
    i +=  [0]*1

print(lst)

the result is:

[[1, 3, 3], [2, 2, 2], [3, 2, 0]]
  • I think you copy/pasted the same code twice – ShadowMitia Jul 26 '21 at 15:53
  • 1
    `a = a + b` and `a += b` are simply not the same. `+` and `+=` are entirely independent operators, that any type can implement as they please with the appropriate dunder methods. For most built-in mutable types, `a += b` is a mutation on `a`. – user2390182 Jul 26 '21 at 15:56

0 Answers0