-1

I am having the following code:

file = open('MyCSV.csv') # this read the Headers name
reader = csv.reader(file)
Data = next(reader,None)
Data = Data[1:]
DataTmp = Data


for item in DataM: # DataM is a list with one element from Data
    Data.remove(item) #remove one item


#
print(len(Data))
print(len(DataTmp))

So, I open MyCSV.csv file, read the header line, and store it in the variable Data. I also made a copy of Data by DataTmp. Originally, the list Data has 10 elements.

Then, I removed one element from Data.

Now, I expect that the length of Data is 9 and the length of DataTmp is still 10. However, I get the answer that the length of DataTmp is 9 too. Why? I never changed DataTmp and I defined it before I remove an element from Data.

Thanks for your help!

Covepe
  • 39
  • 1
  • 6
  • 4
    `DataTmp = Data` makes those the *same object*. That doesn't make a copy. Effecting one will effect the other. – Carcigenicate Jan 29 '19 at 13:37
  • @Carcigenicate Thank you! Now I understood. I used to use Matlab instead of python, and I guess this is the first 'big' difference I learned. – Covepe Jan 29 '19 at 13:52
  • Yes, I'm pretty sure only a few days ago I saw a similar question from someone else coming from MATLAB. This seems to be a common point of confusion. – Carcigenicate Jan 29 '19 at 15:00

1 Answers1

0

Important change is

import copy

AND

DataTmp = copy.copy(Data) # Use this instead of direct assignment.

INSTEAD OF

DataTmp = Data

Use below code.

import copy

file = open('MyCSV.csv') # this read the Headers name
reader = csv.reader(file)
Data = next(reader,None)
Data = Data[1:]
# DataTmp = Data
DataTmp = copy.copy(Data) # Use this instead of direct assignment.

for item in DataM: # DataM is a list with one element from Data
    Data.remove(item) #remove one item

#
print(len(Data))
print(len(DataTmp))
Anup Yadav
  • 2,825
  • 3
  • 21
  • 30