Issue
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
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]))
Answered By – ArchAngelPwn
Answer Checked By – Jay B. (BugsFixing Admin)