Multidimensional list initialization using replication is error prone Low

Replicating a list using replication operator creates references to the existing objects, not copies, which could introduce bugs. We recommend that you create a list of the desired length and then fill in each element with a newly created list, or use list comprehension.

Detector ID
python/multidimension-list-using-replication@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def error_prone_multidimensional_list_noncompliant():
2    # Noncompliant: initialises a multidimensional list using replication.
3    multi_dimension_list = [[1]]*3

Compliant example

1def error_prone_multidimensional_list_compliant():
2    # Compliant: avoids initialising a multidimensional list using replication.
3    multi_dimension_list = [[1 for x in range(2)] for y in range(3)]