Home > Enterprise >  Why is my "while" function causing an infinite loop?
Why is my "while" function causing an infinite loop?

Time:03-04

I am trying to create a function to double all values in a list. However, when I run this I get an infinite loop. Here's my code:

def double_values_in_list ( ll ): 
    i = 0
    while ( i < len(ll) ): 
        ll[i] = ll[i] * 2 
        print ( "ll[{}] = {}".format( i, ll[i] ) )
    return ll

CodePudding user response:

You are not incrementing i at any point inside your while loop so your i will always remain 0 because you initialized it with 0 at start thus i will always be less than the length of your list ll and hence the infinite loop.

consider replacing your method like this

def double_values_in_list ( ll ): 
    i = 0
    while ( i < len(ll) ): 
        ll[i] = ll[i] * 2
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i = i   1
    return ll

CodePudding user response:

Because your I never actually increases in this while loop. If you really want to do it this way you can just add a i = 1 to the end of your function

def double_values_in_list ( ll ): 
    i = 0
    while (i<len(ll) ): 
        ll[i] = ll[i] * 2 
        print ( "ll[{}] = {}".format( i, ll[i] ) )
        i  = 1
    return ll

print(double_values_in_list([1, 2]))

However, this is a lot of extra steps that you don't need to take, you can simply run a pythonic for loop to make things a lot easier on yourself

def double_values_in_list (ll): 
    return [x*2 for x in ll]
    

print(double_values_in_list([1, 2]))
  • Related