0

Hi I am new to Python and have an issue with using arrays in class. When using array of strings, when I update one of the arrays with a string - all the other array entries get the same value. Your kind guidance will be appreciated. I am showing below the working code - without using arrays and then the same using arrays (which is not working).

#Working Code:

class sessionData:
    num_threads = 0
    session_id = []
    audio_check_audio_1 = []
    audio_check_audio_2 = []
    audio_check_audio_3 = []


    def __init__(self, id, f1, f2):
        self.id = id


#in main function later on:

      if (session_id not in sessionData.session_id):
            sessionData.audio_check_audio_1.append(wav_file_name1)
            sessionData.audio_check_audio_2.append(wav_file_name1)
            sessionData.audio_check_audio_3.append(wav_file_name1)
            sessionData.session_id.append(session_id)

       else:

            i = sessionData.session_id.index(session_id)

            if (recording_number == '1'):
                sessionData.audio_check_audio_1[i] = wav_file_name1
            elif (recording_number == '2'):
                sessionData.audio_check_audio_2[i] = wav_file_name2
            else:
                sessionData.audio_check_audio_3[i] = wav_file_name3

#Not working code:

class sessionData:
    num_threads = 0
    session_id = []
    audio_check_audio = [[]*3]


    def __init__(self, id, f1, f2):
        self.id = id


#in main function later on:

    if (session_id not in sessionData.session_id):

        sessionData.session_id.append(session_id)
        sessionData.audio_check_audio.append([wav_file_name[0],'',''])

    else:

         i = sessionData.session_id.index(session_id)

         for x in range 3:

             sessionData.audio_check_audio[i][x] = reg_wav_file[x]
Anurag
  • 1

1 Answers1

0

When you create a list using multiplication like this:

audio_check_audio = [[]*3]

The three sub-lists are actually three identical references to the same list object, and updating one of them will update all of them.

To get around this, don't use multiplication:

audio_check_audio = [[],[],[]]

See this question for more details.

John Gordon
  • 29,573
  • 7
  • 33
  • 58