Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where goes wrong in this list manipulation?

Tags:

python

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?


1 Answers

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.

like image 124
mdml Avatar answered Jan 29 '26 13:01

mdml



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!