Site Search:

does [[0]*4]*3 do the same as [[0 for _ in range(4)] for _ in range(3)] in python3?

 While [[0]*4]*3 may seem like a concise way to create a 3x4 matrix filled with zeros, it has a subtle issue that may lead to unexpected behavior. Using this approach creates three references to the same inner list, rather than three independent lists. As a result, if you modify one row, you'll end up modifying all the rows.

Consider the following example:

python
matrix = [[0]*4]*3 matrix[0][0] = 1 
print(matrix)

You might expect the output to be a matrix with a 1 in the top-left corner, like this:

lua
[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

However, the actual output will be:

lua
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

To avoid this issue, it's better to use nested list comprehensions, as shown in the previous example:

python
matrix = [[0 for _ in range(4)] for _ in range(3)]

This way, each row is an independent list, and modifying one row won't affect the others.