Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is List Variable Changing?

I have a function and its work correct. It can calculate correct only send by one by. But I want to append every result in a list. The list variable is changing when every calculate. Why is changing appened list data ?

`

PLCdevice = {
    '32DI': 0,
    '16DI': 0,
    '8DI': 0
}
PLCList = []

def PLCcal(DIneed ):
    DIteklif = 12
    DItoplam = 0
    for i in range(0, 320, 8):
        DIyedek = DIteklif - DIneed
        DIoran = DIyedek / DIneed
        if DIoran > 0.26:
            break
        DIteklif = DIteklif + 8

    DIteklif = DIteklif -12
    DIteklif = DIteklif / 8

    if DIteklif / 4 >= 1 :
        x = DIteklif / 4
        PLCdevice['32DI'] = int(x)
        DIteklif = DIteklif - (int(x)*4)
    if DIteklif / 2 >= 1 :
        x = DIteklif / 2
        PLCdevice['16DI'] = int(x)
        DIteklif = DIteklif - (int(x)*2)
    if DIteklif == 1 :
        x = DIteklif / 1
        PLCdevice['8DI'] = int(x)
        DIteklif = DIteklif - (int(x)*1)
    return PLCdevice

PLCList.append(PLCcal(32))
print(PLCcal(32))
PLCList.append(PLCcal(85))
print(PLCcal(85))
PLCList.append(PLCcal(411))
print(PLCcal(411))
print(PLCList)

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I try calculate result and store result in a list. But appened data is changing.

>Solution :

Dictionaries are mutable objects, and PLCdevice is a global variable, so every time you change it in PLCcal you are changing other references too which in this case are the values you are appending.

You can simply create PLCdevice at the beginning of PLCcal

def PLCcal(DIneed ):
    PLCdevice = {
        '32DI': 0,
        '16DI': 0,
        '8DI': 0
    }
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading