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
In the first case, you are rebinding the name
ato a new value, so the variableabefore the loop is not the same object as the variableainside and after the loop. The loop is able to iterate on the original value ofa.But in the second case, you are not rebinding the name.
ais the same object throughout the code. And so the loop iterates over a list that grows endlessly bigger.