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.
1def error_prone_multidimensional_list_noncompliant():
2 # Noncompliant: initialises a multidimensional list using replication.
3 multi_dimension_list = [[1]]*3
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)]