Junior — Middle
What will happen if a `for` loop iterating over a list is executed and the list changes during iteration?
sobes.tech AI
Answer from AI
If during a for loop iteration over a list the list is modified (for example, elements are added or removed), the behavior depends on how the loop is organized.
In Python, an iterator is created during list iteration, which accesses elements by index. If the list is modified during iteration, it can lead to:
- Skipping some elements or re-iterating over elements.
- Errors if the length of the list changes.
Example:
lst = [1, 2, 3, 4]
for x in lst:
print(x)
if x == 2:
lst.remove(3) # modifying the list during iteration
In this example, the element 3 will be removed, and the iteration may skip some elements or behave unpredictably.
It is recommended not to modify the list during iteration. If modification is necessary, it is better to iterate over a copy:
for x in lst[:]: # copy of the list
if condition:
lst.remove(x)