[issue22075] Lambda, Enumerate and List comprehensions crash

Ned Deily report at bugs.python.org
Sat Jul 26 04:46:41 CEST 2014


Ned Deily added the comment:

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!

----------
nosy: +ned.deily
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue22075>
_______________________________________


More information about the Python-bugs-list mailing list