-1

Basically, wanted to iterate over a list of numerical data to change it's contents, where the numerical at the start of the list is moved to the last, and then the data is shifted to the left. Whilst I have achieved this, as the printed contents of the loop gives the desired results, when trying to append the contents of said loop to said dictionary, it only does this for the final iteration. Here's my code:

minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}

def patterns(scale):
    for i in scale:
        print (scale)

        scale.insert(len(scale),scale[0])
        del(scale[0])

        MNP['scale degree'].append(scale)

using the function patterns, this is the output:

>>> patterns(minor)

the list, minor, is at the top of the page by the way.

output:

[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 1]
[3, 4, 5, 6, 1, 2]
[4, 5, 6, 1, 2, 3]
[5, 6, 1, 2, 3, 4]
[6, 1, 2, 3, 4, 5]

Yet when I try to print the contents of the list, scale degree, in the MNP dict, the result is:

MNP['scale degree'] [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]]

I am very perplexed by this result, it's as if the output changes depending on the operation called upon it?

Thank you for any help in advance. It's also worth noting that I've been stuck with this for a good amount of time, so if there's any resources out there that may help me understand similar occurrences i certainly wouldn't pass that up.

Jim Jam
  • 713
  • 4
  • 10
  • 22
  • You are filling `MNP['scale degree']` with *references to the same list object*. – jonrsharpe Nov 07 '14 at 08:58
  • possible duplicate of [Python: list of lists](http://stackoverflow.com/questions/11487049/python-list-of-lists) – jonrsharpe Nov 07 '14 at 09:01
  • Hi jon, thankyou very much for the feedback, do you know any around this? Oh, by the way, am not too sure what a reference is, at least in this context, but i'll look into straight away. – Jim Jam Nov 07 '14 at 09:24
  • If you read the duplicate I've linked to, the answers explain just that. – jonrsharpe Nov 07 '14 at 09:25

1 Answers1

-1

The reason this happens is because what you store in MNP['scale degree'] is only a reference to scale. So when you change scale, so do the entries in MNP['scale degree']. What you need to do to avoid this is copying scale each time you append it (i.e. creating a new list instead of adding a reference). You can do this with the copy module:

import copy

minor=[1,2,3,4,5,6]
MNP = {'scale degree' : []
}

def patterns(scale):
    for i in scale:
        print (scale)

        scale.insert(len(scale),scale[0])
        del(scale[0])

        MNP['scale degree'].append(copy.copy(scale))

patterns(minor)
print(MNP['scale degree'])
greschd
  • 606
  • 8
  • 19