Home > database >  Iterating over list creates endless loop and extends list even though it should not
Iterating over list creates endless loop and extends list even though it should not

Time:02-11

I iterate over a Sublist (A). A has a defined lenght. Then, i extend another list (B) with the values of (A). For some reason, the first sublist (A) gets extended by the value i extend the other list (B) by.

I have absolutly no idea why this would happen and I'd be very thankfull for help regarding this issue.

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []

    for i in range(len(A)):
        for element in A[i][0]:

            if B == []:
                B.extend(A[i])

            else:
                if element in B[0]:
                    for e in A[i][0]: #Endless loop, A[i][0] gets extended by value of e
                        B[0].extend([e])

CodePudding user response:

You were appending a shallow copy of A's sublists into B. This means that when you were changing B in the last loop, you were actually also changing elements of A.. so A just kept growing and the loop kept iterating.

To avoid it, use deepcopy from the copy module - it creates an actual, independent copy of As lists so now when you change them through B, only B will have them,

import copy

combinations_list = [[[[1, 0], [], -3], [[0, 2], [], -3], [[2, 1], [], -3], [[0, 3], [], -3]]]

for A in combinations_list:
    B = []
    for i in range(len(A)):
        for element in A[i][0]:
            print(B)
            if B == []:
                B.extend(copy.deepcopy(A[i]))
            else:
                if element in B[0]:
                    for e in A[i][0]:
                        B[0].append([e])

CodePudding user response:

After you do B.extend(A[i]), B[0] references the same list instance as A[0][0]. So ,when you get to B[0].extend([e]), you're actually adding to A[0][0] as well. The loop for e in A[i][0]: for the first i will never end because you are adding to A[0][0] at every iteration.

  • Related