A nested list is given: stocks = [['AAPL', 'MSFT'], ['AMZN', 'TSLA', 'NVDA']] Which of the following code snippets creates a shallow copy of the stocks list? (select three)
A nested list is given:
stocks = [['AAPL', 'MSFT'], ['AMZN', 'TSLA', 'NVDA']]
Which of the following code snippets creates a shallow copy of the stocks list? (select three)
a. import copy
stocks_copy = copy.copy(stocks)
b. stocks_copy = list.copy(stocks)
c. import copy
stocks_copy = copy.deepcopy(stocks)
d. stocks_copy = stocks.copy()
1 Answers
a. import copy
stocks_copy = copy.copy(stocks)
b. stocks_copy = list.copy(stocks)
d. stocks_copy = stocks.copy()
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.