LearnFrenzy
Sign in Take a free test

Lists · Predict the Output · Question 15

A shallow copy of a nested list Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Python program?

main.py
a = [[1, 2], [3]]
b = a.copy()
b[0].append(9)
b.append([7])
b[1] = [0]
print(a, len(b))
  • A [[1, 2], [3]] 3
  • B [[1, 2, 9], [3]] 3 Correct
  • C [[1, 2, 9], [0], [7]] 3
  • D [[1, 2, 9], [3], [7]] 3
Correct Answer: Option B

The inner list [1, 2] is shared, so appending 9 shows in a. Appending to b and replacing b[1] change only b's outer list.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links