0

I have tried reading similar questions on the forum, but I am unable to figure out how append works in the following situation. I believe the empty list is created wrongly?

combinations_run_list = []
improvement_combination_list = [['TEST', 'TEST', 'TEST']]
for combinations_list in improvement_combination_list:
    holder_list = []
    for improvement in combinations_list:
        holder_list.extend([improvement])
        combinations_run_list.append(holder_list)

print(combinations_run_list)

I get the output:

[['TEST', 'TEST', 'TEST'], ['TEST', 'TEST', 'TEST'], ['TEST', 'TEST', 'TEST']]

While I expected following output:

[['TEST'], ['TEST', 'TEST'], ['TEST', 'TEST', 'TEST']]

What can I change in the code snippet to make the output as intended?

EDIT: Here is the solution, a copy needs to be made:

combinations_run_list = []
improvement_combination_list = [['TEST', 'TEST', 'TEST']]
for combinations_list in improvement_combination_list:
    holder_list = []
    for improvement in combinations_list:
        holder_list.extend([improvement])
        holder_list_tmp = holder_list.copy()
        combinations_run_list.append(holder_list_tmp)

print(combinations_run_list)
ConSod
  • 743
  • 8
  • 18
  • 1
    You are appending **a single list object** to the outer list, and keep mutating it. Appending does not create a copy, see the duplicate on how to copy a list. – Martijn Pieters Oct 11 '17 at 12:39
  • Thank you for your answer. However, reading the duplicate I understand that I need to create a copy, but where should I create the copy assignment? – ConSod Oct 11 '17 at 12:59
  • For anyone who needs the answer: I solved it by adding: `holder_list_tmp = holder_list.copy()` and changing `combinations_run_list.append(holder_list)` to `combinations_run_list.append(holder_list_tmp)` – ConSod Oct 11 '17 at 13:04

0 Answers0