Search code examples
python-3.xlistif-statementnested-loops

Python nested IF statement not iterating the entire list


I need some help in understanding why it's not iterating the complete list and how I can correct this. i need to replace some values between list B and List A to do another process. The code is supposed to give me a final list of

b = ['Sick', "Mid 1", "off", "Night", "Sick", "Morning", "Night"] 

I was thinking of 2 nested IF statements, because it's evaluating 2 different things. My code gives me

['Sick', 'Mid 1', 'off', 'Night', 'off', 'Morning', 'Night']

which is correct on element [0], but not on element[4].
I was playing in the indentation of i = i+1

a = ['Sick', 'PR', '', 'PR', 'Sick', 'PR', 'PR']
b = ["off", "Mid 1", "off", "Night", "off", "Morning", "Night"]

i = 0
for x in the_list:
    for y in see_drop_down_list:
        if x =="off":
            if y == "":
                the_list[i] = "off"

            else:
                the_list[i]=see_drop_down_list[i]
i = i + 1           
print (the_list)

Solution

  • You don't need to do double iteration here. Corrected code:

    a = ['Sick', 'PR', '', 'PR', 'Sick', 'PR', 'PR']
    b = ['off', 'Mid 1', 'off', 'Night', 'off', 'Morning', 'Night']
    
    for i in range(len(b)):  # loop through all indexes of elements in "b"
        if b[i] == 'off' and a[i]:   # replace element, if it's "off" and corresponding element in "a" is not empty
            b[i] = a[i]
    
    print(b)
    

    Output:

    ['Sick', 'Mid 1', 'off', 'Night', 'Sick', 'Morning', 'Night']