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)

Questions & AnswersCategory: PythonA 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)
Lokesh Kumar Staff asked 2 years ago

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
Lokesh Kumar Staff answered 2 years ago

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):

  • 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.