Error prone sequence modification Medium

The iterable object for the loop expression is calculated once and remains unchanged despite any index changes caused by the sequence modification. This might lead to unexpected bugs. If you need to modify the sequence, we recommend that you first make a copy, such as by using slice notation.

Detector ID
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1def modifying_list_noncompliant():
2    words = ['cat', 'window', 'defenestrate']
3    # Noncompliant: modifies the same list while iterating over it.
4    for word in words:
5        if len(word) > 6:
6            words.insert(0, word)

Compliant example

1def modifying_list_splice_compliant():
2    words = ['cat', 'window', 'defenestrate']
3    # Compliant: creates new list using splicing, hence loops iterate on one
4    # list, modifying a different list.
5    for word in words[:]:
6        if len(word) > 6:
7            words.insert(0, word)