Home > OS >  Why do i have infinite while loop?
Why do i have infinite while loop?

Time:01-06

I want to cut a list into sublists of a given length (let it be 2 for example). To solve this task i have 1st while loop for the indices in the list and 2nd while loop with the counter of 2. I do increment my counter every cycle of the 2nd while loop and it still gets infinite. Why?

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
i = 0 
chunk = 2 
list2 = [] 
while i < len(list1): 
    element = [] 
    counter = 0 
    while counter <= chunk: 
        element.append(list[i])
        counter  = 1 
    list2.append(element) 
print(list2)

CodePudding user response:

i is set to 0 on line 2 and never changed. Therefore, i < len(list1) will always be True, unless list1 is empty (which it isn't because it is initialized on line 1 and never changed).

CodePudding user response:

I believe its because in your first loop, the condition i < len (list1) will never not be true (i.e will always be true) your second loop will end as counter is incremented, so eventually counter <= chunk will be true the first loop, i is never incremented, so it remains constant (so 0 ) and thus will never exit the while loop

open for correction as I dont have much experience with python

CodePudding user response:

Because in your loop variable i is always 0.

CodePudding user response:

You're never updating your value for i thus it is always 0. Just put i = 1 at the end of your while loop like this:

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
i = 0 
chunk = 2 
list2 = [] 
while i < len(list1): 
    element = [] 
    counter = 0 
    while counter <= chunk: 
        element.append(list[i])
        counter  = 1 
    list2.append(element) 
    i  = 1
print(list2)

Output:

[[list[0], list[0], list[0]], [list[1], list[1], list[1]], [list[2], list[2], list[2]], [list[3], list[3], list[3]], [list[4], list[4], list[4]], [list[5], list[5], list[5]], [list[6], list[6], list[6]]]
  • Related