97 views
1 1 vote

Consider the following Python code:

grid = [[0] * 2] * 3

grid[0][1] = 5
grid[2] = [7, 8]
grid[1][0] = 9

print(grid)

What is the output of the code above?

  1. [[0, 5], [9, 5], [7, 8]]
  2. [[9, 5], [9, 5], [7, 8]]
  3. [[9, 5], [9, 5], [9, 5]]
  4. [[0, 0], [0, 0], [7, 8]]

1 Answer

1 1 vote

The expression $\texttt{[[0] * 2] * 3}$ creates $3$ references to the same inner list.

So after $\texttt{grid[0][1] = 5}$, the shared inner list becomes:

[0, 5]

At this point, all $3$ rows appear as $\texttt{[0, 5]}$ because they refer to the same list.

Then $\texttt{grid[2] = [7, 8]}$ replaces only the third row with a new separate list.

Now $\texttt{grid[0]}$ and $\texttt{grid[1]}$ still share the same list, but $\texttt{grid[2]}$ is separate.

So $\texttt{grid[1][0] = 9}$ changes both the first and second rows.

Therefore, the output is:

[[9, 5], [9, 5], [7, 8]]

Correct Option: B

Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
107
107 views
GO Classes asked Jun 5
107 views
Consider the following Python code:data = [[1, 2, 3], [4, 5], [6]] result = [x for row in data for x in row if x % len(row) == 0] print(result)What is the output of the c...
1 1 vote
1 1 answer
93
93 views
GO Classes asked Jun 5
93 views
Consider the following Python code:funcs = [] for i in range(3): funcs.append(lambda x: x + i) result = [f(10) for f in funcs] print(result)What is the output of the code...
1 1 vote
1 1 answer
98
98 views
GO Classes asked Jun 5
98 views
Consider the following Python code:def make_list(): data = try: return data finally: data.append(2) result = make_list() print(result)What is the output of the code abo...
1 1 vote
1 1 answer
92
92 views
GO Classes asked Jun 5
92 views
Consider the following Python code:values = [1, 2, 3] gen = (x * 2 for x in values) values.append(4) first = list(gen) values.append(5) second = list(gen) print(first, se...