Why is my .append () list changing the value of each member variable to a new variable?

In my function, I create unique variables that I want to add to the list. But whenever I add the next variable, the values ​​of all other variables inside the list change to the new one.

Here's my code:

def make_list_of_data_transfer_objects(iFile, eFile, index_of_sheet):

    iBook = open_workbook(iFile)
    iSheet = iBook.sheet_by_index(0)

    eBook = open_workbook(eFile)
    eSheet = eBook.sheet_by_index(index_of_sheet)

    DataSet = namedtuple('DataSet', 'line_num data_list')

    list_objects = []
    temp_line_num = 99999
    temp_data = [0]*5

    for row_index in range(eSheet.nrows):
        temp_data[0] = eSheet.cell(row_index,0).value
        temp_data[1] = eSheet.cell(row_index,1).value
        temp_data[2] = eSheet.cell(row_index,2).value
        temp_data[3] = eSheet.cell(row_index,3).value
        temp_data[4] = eSheet.cell(row_index,4).value
        for row_index2 in range(iSheet.nrows):
            if temp_data[0] == iSheet.cell(row_index2,0).value:
                temp_line_num = row_index2
                temp_object = DataSet(temp_line_num, temp_data)

                list_objects.append(temp_object)

    #print list_objects #every object is the same

    list_objects.sort(key = lambda tup: tup[0]) #sort by line number

    return list_objects

      

+2


source to share


1 answer


Edit

temp_object = DataSet(temp_line_num, temp_data)

      

to

temp_object = DataSet(temp_line_num, temp_data[:])

      



or

temp_object = DataSet(temp_line_num, list(temp_data))

      

By passing temp_data

in DataSet

, you don't create a copy of the list, you just reuse the existing one. By using [:]

or list()

, you create a copy instead.

+7


source







All Articles