It may be hard to see what's going on with the code written as a list comprehension. We could expand it out to something roughly equivalent and print the first n iterations:
def main():
lista =[1, 4, 5 , 5, 6 , 3 ,1]
def ins(x):
return lista.insert(x,0)
for idx, v in enumerate(lista):
if v == 5:
ins(idx)
print(idx, lista)
if idx > 10:
break
if __name__ == '__main__':
main()
(2, [1, 4, 0, 5, 5, 6, 3, 1])
(3, [1, 4, 0, 0, 5, 5, 6, 3, 1])
(4, [1, 4, 0, 0, 0, 5, 5, 6, 3, 1])
(5, [1, 4, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(6, [1, 4, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(7, [1, 4, 0, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(8, [1, 4, 0, 0, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(9, [1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(10, [1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
(11, [1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 6, 3, 1])
Because the list is mutating by inserting the 0 before the 5, once the 5 entry is found, it keeps "moving" to the right so the loop never terminates and lista keeps expanding until Python runs out of memory. Don't do that! |