Search code examples
pythonfor-in-loop

for in loop over list (with +=) coding beginner


a = [1,2,3]
for num in a:
  a = a + [num]
print(a)

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

a = [1,2,3]
for num in a:
  a += [num]
print(a)

>>>

The first code works as expected, so I assume the below code will work the same, but it didn't print anything. Not even a Error message.

Question: I did some research in stackoverflow on the use of +=, but still got confused on what's the difference between the add and iadd


Solution

  • In the first case, you are rebinding the name a to a new value, so the variable a before the loop is not the same object as the variable a inside and after the loop. The loop is able to iterate on the original value of a.

    But in the second case, you are not rebinding the name. a is the same object throughout the code. And so the loop iterates over a list that grows endlessly bigger.