91 views
2 2 votes

Consider the following Python code:

matrix = [[1, 2], [3, 4]]
copy_matrix = matrix[:]

copy_matrix[0][1] = 99
copy_matrix[1] = [7, 8]

print(matrix, copy_matrix)

What is the output of the code above?

  1. [[1, 2], [3, 4]] [[1, 99], [7, 8]]
  2. [[1, 99], [7, 8]] [[1, 99], [7, 8]]
  3. [[1, 99], [3, 4]] [[1, 99], [7, 8]]
  4. [[1, 2], [7, 8]] [[1, 99], [7, 8]]

1 Answer

0 0 votes

The statement $\texttt{copy\_matrix = matrix[:]}$ creates a shallow copy of the outer list.

This means $\texttt{matrix}$ and $\texttt{copy\_matrix}$ are different outer lists, but the inner lists are still shared.

So $\texttt{copy\_matrix[0][1] = 99}$ changes the first inner list, which is shared by both outer lists.

matrix = [[1, 99], [3, 4]]

Then $\texttt{copy\_matrix[1] = [7, 8]}$ replaces only the second element of $\texttt{copy\_matrix}$ with a new list.

It does not change $\texttt{matrix[1]}$.

Therefore, the output is:

[[1, 99], [3, 4]] [[1, 99], [7, 8]]

Correct Option: C

Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
89
89 views
GO Classes asked Jun 18
89 views
Consider the following Python code:def update(lst): lst.append(4) lst[0] = lst[0] + 10 lst = [100, 200] lst.append(300) return lst nums = [1, 2, 3] result = update(nums) ...
1 1 vote
1 1 answer
99
99 views
GO Classes asked Jun 18
99 views
Consider the following Python code:a = [10, 20] b = a c = b b[0] = 99 c.append(30) print(a, b, c, a is c)What is the output of the code above?[10, 20] [99, 20] [99, 20, 3...
0 0 votes
1 1 answer
88
88 views
GO Classes asked Jun 18
88 views
Consider the following Python code:x = 5 y = x x = x + 1 s = "go" t = s s = s.upper() print(x, y, s, t, x is y, s is t)What is the output of the code above?6 5 GO go Fals...
0 0 votes
2 2 answers
108
108 views
GO Classes asked Jun 18
108 views
Consider the following Python code:a = [1, 2] b = a c = [1, 2] print(a is b, a is c, a == c)What is the output of the code above?True True TrueTrue False TrueFalse False ...