do not modify a dictionary while iterating on it

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: python-best-practices/collection-while-iterating

Language: Python

Severity: Error

Category: Error Prone

Description

Never update a dictionary while iterating on it. If you wish to update the dictionary, create a new dictionary from the existing values.

Non-Compliant Code Examples

i = 0
for element in my_list:
    my_list["stuff"] = i  # modifying a dictionary while iterating
    i += 1

Compliant Code Examples

i = 0
new_list = {}
for element in my_list:
    new_list["stuff"] = i  # putting value to a new dictionary
    i += 1
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis