Week 5 regarding exercise problem on lists

in explaining about deep copy in the below line of code

                                            temp=[item[:] for item in A]

sir said that item[:] will create a list but already item in A are list why we need to create again a list

i am asking like why following will not work
temp=[item for item in A]

Here is an explanation:
A is a 2 dimensional array, rather a 2-D list.
e.g. A = [[1,2,3],[4,5,6],[7,8,9]]

In this line of code,
temp=[item for item in A]
item is a list again
if you copy an item as is then you are doing a shallow copy of each list within A.

See the example here:

A = [[1,2,3],[4,5,6],[7,8,9]]

#Shallow copy of lists within A
temp = [item for item in A]
print('temp:', temp)

#Modify one element within a list
A[0][0]=0
print('temp:', temp)
#Output
temp: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
temp: [[0, 2, 3], [4, 5, 6], [7, 8, 9]]

But if you do, temp = [item[:] for item in A]
From a 2-D list A, you are taking an item which is a 1-D list, and doing a deep copy of that 1-D list into temp.

See the code here:

A = [[1,2,3],[4,5,6],[7,8,9]]

#Deep copy of lists within A
temp = [item[:] for item in A]
print('temp:', temp)

#Modify one element within a list
A[0][0]=0
print('temp:', temp)
#Output
temp: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
temp: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Observe that we don’t see 0 in the first element of first list.

Hope this answers.

2 Likes