Arnoald Hagel Arnoald Hagel - 1 month ago 8
Python Question

Converting to a for loop

I'm curious as to how this can be rewritten as a for loop?

def decode (lst):
i=0
result=[]
while i<len(lst):
result+=([lst[i]]*lst[i+1])
i+=2
return(result)
print(decode([4,6,2,1,9,5,5,2,4,2]))

Answer

Assuming that this is Python code (as it looks like) you can just specify the step in the range function.

def decode (lst):
    result = []
    #More common syntax if not using python for(i = 0; i < len(lst); i += 2):
    for i in range(0, len(lst), 2):
        result += ([lst[i]] * lst[i+1])
    return result
print(decode([4,6,2,1,9,5,5,2,4,2]))

You will also want to add some error checking to make sure that your array has an even number of elements or this and your original example will fail.

Comments