Fix RuntimeError: set changed size during iteration