0

I have a dictionary object with three keys. Each key contains three RGB values.

>>> dictObj = {}
>>> dictObj['key1'] = ["123,12,43", "42,34,1", "38,225,132"]
>>> dictObj['key2'] = ["234,92,109", "227,5,229", "156,4,2"]
>>> dictObj['key3'] = ["15,123,82", "128,11,130", "78,39,1"]

My goal is to take each key's list of RGB values, and take the R of each item, the G of each item and B of each item to create three lists, containing just the R values of all three keys, the G values of all three keys and the B values of all three keys.

I implemented a series of for loops to call each key, split the item in each key's list and attempt to append the R, G and B values to each respective list.

>>> rList=gList=bList=[]
>>> for key in dictObj:
        for RGBval in dictObj[key]:
            RGBval = RGBval.split(',')
            rList.append(RGBval[0])
            gList.append(RGBval[1])
            bList.append(RGBval[2])

I run the loop, however each list, contains the exact same values. I don't understand why this is happening. If I print RGBval[0], RGBval[1] and RGBval[2] within the loop, each iteration shows different, distinct values. However when the three lists are created via the append method, when printed, each list contains the exact same values, this is my output.

>>> print rList
['123', '12', '43', '42', '34', '1', '38', '225', '132', '15', '123'...etc]
>>> print gList
['123', '12', '43', '42', '34', '1', '38', '225', '132', '15', '123'...etc]
>>> print bList
['123', '12', '43', '42', '34', '1', '38', '225', '132', '15', '123'...etc]

How can I create my lists so that they contain the appropriate values for each list? IE, the rList, list, only contains the R values of each key's list items, the gList only contain the G values of each key's list items, etc?

Thanks for your input!

0xhughes
  • 2,703
  • 4
  • 26
  • 38

1 Answers1

4

This doesn't make 3 empty lists!

rList=gList=bList=[]

You just get 3 references to the same list. Just write it as 3 lines

rList = []
gList = []
bList = []
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • I just tested this. It worked perfectly! I thought I was being clever after using that type of declaration in a code golf foray. I changed things up and my code worked as intended. Thanks a ton gnibbler. When it let's me, i'll accept your answer. – 0xhughes Oct 27 '14 at 02:48
  • @0xhughes : Also see SO regular Ned Batchelder's article [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html) and http://stackoverflow.com/q/1132941/4014959 – PM 2Ring Oct 27 '14 at 06:54