Modifying a list


I tried to modify a list without using the range function. The error message says: "The program took too long to finish. Check your code for infinite loops and try again."

I wrote the following code. Why is this an infinte loop?

p = [1, 2, 3]
for a in p:
    b = a * 2
    p.insert(p.index(a), b)
print p


Hi @webpro53038,

As your loop iterates through the list, p, you are adding items to p. Therefore, the loop can never reach the end of the list. In most cases, modifying the length of a list as you iterate through it causes a problem.


Okay, got it. Thanks @appylpye!