Python Forum
Appending to list of list in For loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending to list of list in For loop

I have question regarding for loops and appending to a list in that loop. In a for loop, I am trying to append a list to a list of lists. With each iteration, I modify one of the elements of the list. The code is listed below:

test = []
current = [0, 0]

for i in range(6):
    print('current value: {}'.format(current))
    current[0] += 1 #only increment the value at index 0

print('Test: {}'.format(test))
I print the current value with every iteration for testing purposes. The desired output is Test: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0]]. However, running the code yields the following:
current value: [0, 0] current value: [1, 0] current value: [2, 0] current value: [3, 0] current value: [4, 0] current value: [5, 0] Test: [[6, 0], [6, 0], [6, 0], [6, 0], [6, 0], [6, 0]]
It seems like the current value is correctly incremented, however the final output (test) is a list of lists containing only the last value taken by current.

Can anyone explain this behaviour, or how I could get the desired output?

current is a (mutable) list. When you append it to test each time, you are appending the same object. When you change one of the values of that object on line 7, all the views of that object are changed also.

You want to have 6 different lists in test, not 6 instances of the same list.

You could append a copy of that list. Some options:
from copy import copy
# or
Thanks for your reply! Makes sense now and fixed my code!

Possibly Related Threads…
Thread Author Replies Views Last Post
  Why changing data in a copied list changes the original list? plumberpy 3 360 Aug-14-2021, 02:26 AM
Last Post: plumberpy
  Compile list of dictianories out of another list of dictianories by certain keys CatorCanulis 10 906 Jun-10-2021, 08:35 PM
Last Post: perfringo
  Time.sleep: stop appending item to the list if time is early quest 0 502 Apr-13-2021, 11:44 AM
Last Post: quest
  Looking for a way to loop until user enters from a list? PythonW19 7 837 Mar-21-2021, 08:56 PM
Last Post: PythonW19
  Order a list with successive permutations based on another list yvrob 3 747 Mar-19-2021, 08:20 AM
Last Post: supuflounder
  Saving list in a list quest_ 3 893 Mar-10-2021, 09:58 AM
Last Post: quest_
  Reading and appending list MrSwiss 1 471 Mar-01-2021, 09:01 AM
Last Post: Serafim
Star Convert Bytearray into List using list() Shlok 2 651 Feb-18-2021, 10:44 AM
Last Post: deanhystad
  For Loop with List Comprehension muzikman 25 1,836 Dec-18-2020, 10:45 PM
Last Post: muzikman
  Adding List Element if Second part of the List Elements are the Same quest_ 3 748 Nov-25-2020, 04:33 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020