do not modify a dictionary while iterating on it

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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