Search code examples
pythonincrementnested-for-loop

python nested for loop add incremented value by first loop


Imagine this situation:

cable1 = ['label_11','label_12','label_13']
cable2 = ['label_21','label_22','label_21']
cable3 = ['label_31','label_32','label_33']
cables = [cable1,cable2,cable3]
number = 0

for cable in cables:
    number += 1
    for label in cable:
        if label.find('3') != -1:
            label = str(number)+'_'+label
            print(f'label: {label}')

prints:

label: 1_label_13
label: 3_label_31
label: 3_label_32
label: 3_label_33

instead of:

label: 1_label_13
label: 2_label_31
label: 2_label_32
label: 2_label_33

How can I make the third iteration over cable to become a 2 label?


Solution

  • It's because you're increasing the count of variable number in each iteration. You can control this increment via flag. Something like this may help -

    cable1 = ['label_11','label_12','label_13']
    cable2 = ['label_21','label_22','label_21']
    cable3 = ['label_31','label_32','label_33']
    cables = [cable1,cable2,cable3]
    number = 1
    
    for cable in cables:
        flag = 0
        for label in cable:
            if label.find('3') != -1:
                label = str(number)+'_'+label
                print(f'label: {label}')
                flag = 1
        if flag:
            number += 1 # only increase the value if the item is found.