Home > Software design >  While loop stops after 1 iteration and don`t remove all values
While loop stops after 1 iteration and don`t remove all values

Time:10-27

There are 3 lists: c_o, C_x and C_y. List C_x and list C_y have the same number of values. It has also known that all values in c_o are included in the list C_x.

c_o = [1, 2, 3, 4]
C_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
C_y = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]

I want to compare values from list c_o with the values in the list C_x. If the value in c_o matches the value in C_x, I want to remove that value from list C_x and also remove the value at the same position in the list C_y.

c_o = [1, 2, 3, 4]
C_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
C_y = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]

b = 0
while b < len(C_x):
    if c_o[1] == C_x[b]:
        C_x.remove(C_x[b])
        C_y.remove(C_y[b])          
    b =1  

If I manually change [number] in if c_o[0] == C_x[b]: to 0, 1, 2... code is working fine and removes corresponding values from lists C_x and C_y. However, when I want to make it automatic and adding the second while loop, it stops after removing first value. It gives:

2 22
3 33
4 44
5 55
6 66
7 77
8 88
9 99
10 111

Instead of:

5 55
6 66
7 77
8 88
9 99
10 111

Code with added loop:

c_o = [1, 2, 3, 4]
C_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
C_y = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]
a = 0
b = 0
while a < len(c_o):  
    while b < len(C_x):
        if c_o[a] == C_x[b]:
            C_x.remove(C_x[b])
            C_y.remove(C_y[b])          
        b =1     
    a =1

Can please anyone explain, why while loop does not work properly here?

CodePudding user response:

I modified your variables but this is what I came up with :

l1 = [1, 2, 3, 4]
l2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l3 = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]

'''If the value in c_o matches the value in C_x, 
I want to remove that value from list C_x and also remove the value at the same position in the list C_y.'''

i = 0
count = 0
while i < len(l1):
    if l1[i] in l2:
        count  = 1
    else:
        continue
    i =1
print(l3[count:])

CodePudding user response:

You need to move b = 0 inside the 1st loop

c_o = [1, 2, 3, 4]
C_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
C_y = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]
a = 0
while a < len(c_o):
    b = 0 
    while b < len(C_x):
        if c_o[a] == C_x[b]:
            C_x.remove(C_x[b])
            C_y.remove(C_y[b])          
        b =1     
    a =1

UPD: as well as if you remove an element from an array which is iterated it's needed to use reverse order like this

c_o = [1, 2, 3, 4]
C_x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
C_y = [11, 22, 33, 44, 55, 66, 77, 88, 99, 111]
b = len(C_x) - 1
while b >= 0:
    a = len(c_o) - 1     
    while a >= 0:  
        if c_o[a] == C_x[b]:
            C_x.remove(C_x[b])
            C_y.remove(C_y[b])          
        a-=1     
    b-=1
  • Related