-3

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]]

I dont know how come this long list comes in. I am new to python struck to trace its behavior. Here is the code

data = [10, 20, 30]
list1 = list2 = list3 = list()
lists = [list1, list2, list3]

for i in range(len(data)):
  lists[i].append(data[i])
  print '-------------------'
  print 'at %s' %(i)
  print '  List:  %s' % (lists)
  print '  Data: %s' %  (data[i])

And response

-------------------
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
MaNKuR
  • 2,578
  • 1
  • 19
  • 31
  • @lejlot, No its not complete duplicate of the post you mentioned. here i need the explanation explained perfectly in the Post mentioned by Rohit – MaNKuR Sep 21 '13 at 08:04
  • 1
    It is explained in both questions, while in the one marked by Rohit is actually a bit different, as it also shows how the list multiplication operation treats the references (which is **not the case** here). But it is not really important, either way - it is a duplicate question, and already has a good answers on the site, hope they helped you understand the issue :) – lejlot Sep 21 '13 at 08:07

2 Answers2

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.

Community
  • 1
  • 1
lejlot
  • 64,777
  • 8
  • 131
  • 164
0

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.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
  • Yes, you are right, i have executed this code i dont know how many times to the terminal using ipython because of that got that response but now i have improved its answer for i in range(len(data)): ....: lists[i].append(data[i]) ....: print '-------------------' ....: print 'at %s' %(i) ....: print ' List: %s' % (lists) ....: print ' Data: %s' % (data[i]) – MaNKuR Sep 21 '13 at 07:54
  • Thanks for your hint and now its all cear – MaNKuR Sep 21 '13 at 07:54