Practice mode Python

What is the output of the following Python code? grid = * 2] * 2; grid = 1; print(grid)

Correct answer D. [[1, 0], [1, 0]]

Explanation

Multiplying a list copies references, not objects, so both rows of grid refer to the same inner list. Changing grid[0][0] therefore appears in both rows. To build independent rows use a comprehension such as [[0] * 2 for _ in range(2)], which creates a new inner list on each iteration.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.