Modifying a Python list while iterating: Only append is safe

Modifying a Python list while iterating: Only append is safe

Think you can’t modify a Python list while iterating? You can append to it:

mylist = [10, 20, 30]
for i in mylist:
    print(i)
    if i < 100:
        mylist.append(i ** 2)

This prints 10, 20, 30, 100, 400, and 900.

BUT don’t insert or remove. That’ll cause real trouble.