do not modify a dictionary while iterating on it

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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

PREVIEWING: may/unit-testing