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 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
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):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.