Skip to content Skip to sidebar Skip to footer

Python Uncaught List Variable's Behavior

Can anyone please explain the output i am getting. As the first time the variable lists is blank but when data[i] i.e 10 appended to the lists[i] it becomes List: [[10], [10, [10]

Solution 1:

This is an invalid question (it contains output of other code then provided), you are probably running the second (after initialization) part multiple times in your interpreter. The output of your code should look like

-------------------
at 0
  List:  [[10], [10], [10]]
  Data: 10
-------------------
at 1
  List:  [[10, 20], [10, 20], [10, 20]]
  Data: 20
-------------------
at 2
  List:  [[10, 20, 30], [10, 20, 30], [10, 20, 30]]
  Data: 30

tested on Python 2.7

The aspect of "multiple additions" has been already answered in this question so I do not duplicate this information.


Solution 2:

Pretty sure that output is not from the complete code you posted. It looks a whole lot like the list you append to (you have only one, though all the names list1, list2, list3 and lists[i] refer to it) has not been created fresh for each run of the loop, which is done by the second and third line of the code you posted.


Post a Comment for "Python Uncaught List Variable's Behavior"