-2

Consider it as creating rows in database table. I have the list of items. Let's call it a row. One of them is list as well. I need to create multiple rows containing each element from internal list and then add them to the new bigger list (rows):

rows = []
row = [1, 2, [3, 4, 5]]

temp_row = None
for i, v in enumerate(row):
    if isinstance(v, list):
        print i, v
        for j in v:
            temp_row = row
            temp_row[i] = j
            print temp_row
            rows.append(temp_row)

print rows

But the output looks like that:

2 [3, 4, 5]
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[[1, 2, 5], [1, 2, 5], [1, 2, 5]]

You can see that temp_row printed before adding it to the rows looks correct. So why temp_rows appended to the final array are not? I tried to workaround it with dictionary, but the output was similar.

piwnk
  • 11
  • 1
  • 3

1 Answers1

0

The bug is in the line

temp_row = row

You are asigning the reference of temp_row to the reference of row. That means they point at exact the same list. If you change temp_row, you wil change row. So inserting three temp_rows with exactly the same reference will give you that output. To change it, paste [:] after row. Like this:

rows = []
row = [1, 2, [3, 4, 5]]

temp_row = None
for i, v in enumerate(row):
    if isinstance(v, list):
        print i, v
        for j in v:
            temp_row = row[:]
            temp_row[i] = j
            print temp_row
            rows.append(temp_row)

print rows
Vincent Beltman
  • 2,064
  • 13
  • 27