0

Given the code

  def sumset(a, b):
    bands=[[0, 0]]*len(a)*len(b)
    current=-1
    for ba in a:
      for bb in b:
        current+=1
        bands[current][0]=ba[0]+bb[0]
        bands[current][1]=ba[1]+bb[1]
        print(bands[current])

    print(bands)

The output of sumset([[1,2], [2,4]], [[0,1], [8, 9]]) gives

[1, 3]
[9, 11]
[2, 5]
[10, 13]
[[10, 13], [10, 13], [10, 13], [10, 13]]

I cannot understand why bands is filled with bands[3].

EDIT: I am using Python 3.4.2 on Ubuntu 14.10.

1
  • 2
    use bands = [[0,0] for i in range(len(a)*len(b))] to avoid it. Check the answer below Commented Nov 10, 2014 at 23:39

1 Answer 1

1

By multiplying a list you're creating a copies of the initial list. So when you modify one of them, the changes are transfered into the other copies as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.