Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading