Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my "while" function causing an infinite loop?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading