Home > database >  .append() in python adds everything twice
.append() in python adds everything twice

Time:11-22

I need to create an array of as many positions as rows an Excel sheet has and determine for that position how many files are linked to that row by checking a couple of conditions.

This is the array where I want to put the files and their information.

gallery = [[]] * len(name)

And this is my code:

test_name = []
test_type = []
test_url = []

img_type = ''
for i in range(len(excel.name)):
    for j in range(len(files)):
        if files[j].find(excel.code[i]) > 0:
            print("Found it! ", files[j], " ", excel.name[i], " ", excel.code[i])
            url = storage.upload_plan_image(files[i])
            if files[j].find("Elevation") > 0:
                img_type = 'Elevation'
            elif files[j].find("Floorplan_1") > 0:
                img_type = 'First Floor'
            elif files[j].find("Floorplan_2") > 0:
                img_type = 'Second Floor'
            elif files[j].find("Floorplan_3") > 0:
                img_type = 'Third Floor'
            elif files[j].find("Floorplan_4") > 0:
                img_type = 'Fourth Floor'
            else:
                img_type = 'Other'
            test_name.append([files[j]])
            test_type.append(img_type)
            test_url.append(url)
            excel.gallery[i].append([test_name[i], test_type[i], test_url[i]])

Right now I'm testing with 8 files and 2 rows. Each row should have 4 images each (that's the amount that meets those requirements) but each position of my excel.gallery array has 8 files (which is the total).

My issue is that the items that I append to the items of excel.gallery get added to each sub-list of excel.gallery, not just the one I'm targeting in the loop iteration.

CodePudding user response:

The problem is how you're declaring your gallery array. When you multiply a list by an int (e.g. [[]] * 10), you're not creating a list of ten individual lists, as you might expect. You're actually create a list of references to the one list you originally had. So all the items that look like separate lists are actually the same list.

You can see this in action:

>>> gallery = [[]] * 10
>>> gallery
[[], [], [], [], [], [], [], [], [], []]
>>> gallery[0].append('hello')
>>> gallery
[['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
>>>

Instead, you can use range to create each list individually:

gallery = [[] for _ in range(len(name))]

For example:

>>> gallery = [[] for _ in range(10)]
>>> gallery
[[], [], [], [], [], [], [], [], [], []]
>>> gallery[0].append('hello')
>>> gallery
[['hello'], [], [], [], [], [], [], [], [], []]
>>>
  • Related