Why You Should Never Modify a Dictionary While Looping in Python π
Have you ever tried to modify a dictionary while looping over it in Python—only to get hit with a confusing RuntimeError ? You're not alone. This is a classic Python trap that even experienced developers can fall into. ❗ The Problem my_dict = {'a': 1, 'b': 2, 'c': 3} You might try this: for key, value in my_dict.items(): if value == 2: del my_dict[key] But Python will throw: RuntimeError: dictionary changed size during iteration π Why This Happens Python loops through the internal structure of the dictionary. If you change that structure mid-loop by adding or removing keys, Python raises an error to protect your program from unpredictable behavior. ✅ The Right Way: Loop Over a Copy for key in list(my_dict.keys()): if my_dict[key] == 2: del my_dict[key] By using list(my_dict.keys()) , you're making a safe copy of the keys before the loop begins. Now you can modify the dictionary freely inside the loop. ⚠️...