3

I am manipulating with the lists in Python.

In [52]: myList = [1,2,3,4,5]
In [54]: c=[[]]*10

In [55]: for i, elem1 in enumerate(myList):
   ....:     b = [elem1 + elem2 for elem2 in range(10)]
   ....:     minSum, minSumIndex= min((val, idx) for (idx, val) in enumerate(b))
   ....:     c[minSumIndex].append(elem1)

I am expecting all the elements in myList to be appended to c[0], since elem1+1 always gives the smallest sum.

print c[0]
[1, 2, 3, 4, 5]

print c[1]
[]

print c[2]
[]

...

However, I ended up with this:

In [56]: shape(c)
Out[56]: (10, 5)

In [57]: print c[0]
[1, 2, 3, 4, 5]

In [58]: print c[1]
[1, 2, 3, 4, 5]

In [59]: print c[2]
[1, 2, 3, 4, 5]

In [60]: print c[3]
[1, 2, 3, 4, 5]

In [61]: print c[4]
[1, 2, 3, 4, 5]

In [62]: print c[5]
[1, 2, 3, 4, 5]

Where went wrong?

2 Answers2

4

The source of your confusion is on this line

c=[[]]*10

Here you are creating a list of ten references to the same (initially empty) list. Thus as you append to the list in c[0] later on, you are also appending to every other list in c. Try

c = [ [] for _ in range(10) ]

This will create a new list 10 ten times, so you won't have the same referencing problem.

mdml
  • 22,442
  • 8
  • 58
  • 66
0

Lists in c are all the same object. You need to do at least:

c = [[] for i in xrange(10)]
Nik
  • 420
  • 4
  • 16