Writing to nested list writing in multiple spots?

36 views Asked by At

Hi I'm have this very strange issue with the following code:

def splice_into_blocks(s,bs):
    blocklist = []
    if (len(s)%bs):
        s = s+'0'*(bs-len(s)%bs)
    for i in range((len(s)/bs)+1):
        blocklist.append(list(s[bs*(i):bs*(i+1)]))
    del blocklist[-1]
    return blocklist


bl = splice_into_blocks(crypt, 4)
# print bl

def byte_transpose(blocklist):
    bs = len(blocklist[0])
    blocklist_t = [['0']*len(blocklist)]*bs
    for k1,i in enumerate(blocklist):
        # for k2,j in enumerate(i):
        #     blocklist_t[k2][k1] = j
        blocklist_t[0][k1] = i[0]
    print blocklist_t

byte_transpose(bl)

Specifically in the line

blocklist_t[0][k1] = i[0]

My intuition would that this would only write to list with index 0 in the blocklist_t (so in my case, the first of 4) and leave the other ones alone. However, it is writing the same values to:

  • 0, k1
  • 1, k1
  • 2, k1
  • 3, k1

My actual objective is to use the two lines that I have commented out to transpose this embedded list.

Any and all help appreciated.

1

There are 1 answers

0
DYZ On BEST ANSWER

Operator * makes a list of bs references to the list [['0']*len(blocklist)], not bs copies of [['0']*len(blocklist)]. In other words, there is only one [['0']*len(blocklist)] references as blocklist_t[0], blocklist_t[1], etc. What you need is this:

blocklist_t = [['0']*len(blocklist) for i in range(bs)]