A nested list is given: stocks = [['AAPL', 'MSFT'], ['AMZN', 'TSLA', 'NVDA']] Which of the following code snippets makes a deep copy of the stocks list? (select one)

Questions & AnswersCategory: PythonA nested list is given: stocks = [['AAPL', 'MSFT'], ['AMZN', 'TSLA', 'NVDA']] Which of the following code snippets makes a deep copy of the stocks list? (select one)
Lokesh Kumar Staff asked 2 years ago

A nested list is given:

stocks = [['AAPL', 'MSFT'], ['AMZN', 'TSLA', 'NVDA']]

Which of the following code snippets makes a deep copy of the stocks list? (select one)
a. stock_copy = list.copy(stocks)
 
b. import copy
stocks_copy = copy.deepcopy(stocks)
 
c. import copy
stocks_copy = copy.copy(stocks)
 
d. stocks_copy = stocks.copy()

1 Answers
Lokesh Kumar Staff answered 2 years ago

b. import copy
stocks_copy = copy.deepcopy(stocks)
Explanation:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.