0

So I have a list of lists named list_0. I extract from it a maximum list which I store into list_maximas. Then later in the code I make changes to items of this list_maximas. My problem is that these changes occur in list_0 as well ! I tried making a copy of list_0 : list_1 = list_0.copy() and then extracting it's maximum ...ect, same as before. But even then the changes still appear on list_0 !!

I am sorry if this is confusing. What i want is to have list_0 unchanged when I make changes to the other lists. And more importantly to understand what is the source of the issue so I can avoid it in the future. Thanks for reading me.

EDIT: I marked the relevant lines by a "# Here" in the script.

list_maximas = []
list_0 = []

for stack in range(int(len(os.listdir(os.path.join(DIR, 'croped_stacks')))/2.0)):
    list_0 = []
    with tiff.TiffFile(f'D:\Anis\Mesures\mesures30_03\croped_stacks\stack_D6_{stack*5}.tif') as tif:
        for i, page in enumerate(tif.pages):
            image = page.asarray()
            if stack == 0 :
                list_0.append([stack*5, i-1, np.max(image)]) #cz glitch with the first stack
            else:
                list_0.append([stack*5, i, np.max(image)]) # Here           
        list_maximas.append(max(list_0, key=lambda x: x[2])) # Here

    Objread = open(os.path.join(DIR, 'croped_stacks', f'README_D6_{stack*5}.txt'), "r")
    txtcontent = Objread.read()
    Objread.close()
    for line in txtcontent.split("\n"):
        a_property = line.split('=')
        if "step_size" in a_property:
            step_size = float(a_property[1])
            list_maximas[-1].insert(2, 1000*(step_size*(float(list_maximas_2[0][1]+1.0) - float(list_maximas[-1][1]+1.0 )))) # Here
        if "voltage" in a_property:
            list_maximas[-1].append(float(a_property[1])) # Here
        elif "amperage" in a_property:
            list_maximas[-1].append(float(a_property[1])) # Here



  • 1
    You are currently appending item *references* from `list_0` to `list_maximas`. `list_0.copy()` does not work because it makes a shallow copy of the containing array - that is, it only copies the outer list without copying it's items. But you are modifying it's items, which are references to the `list_0` items. Try copying the specific items `list_maximas.append(max(list_0, key=lambda x: x[2]).copy())` – comonadd Apr 01 '21 at 11:04
  • Yes, it worked !! Thanks a lot. – user14434207 Apr 01 '21 at 11:14

0 Answers0