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

Question:

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

Asked By: JWw

||

Answers:

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.

Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.