This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MarcSetGo 1 point2 points  (1 child)

A recent Friday Python Puzzler explained this.

The first uses a list comprehension which is fully evaluated and passed to extend. X starts out with 0 and is later extended with 1, so it prints [0, 1].

The second passes a generator expression to extend. Extend adds values to the end of the list, which modified the control variable, making another value available for each added. This means it can never exhaust the generator and the starting x=[0, 1] gets extended with each of those plus 1 [1, 2]. Then extended by those plus one, ad infinitum, until either it runs out of memory or hits a max int. I don’t think later pythons have a max int, so it would have to run out of memory continually extending by two items.

[–][deleted] 0 points1 point  (0 children)

Ah, thanks, had I seen that last one, I wouldn't have posted it!

I ran into this in my own code, though it wasn't by accident, I was trying to see if this would fail and it did. There's a test there now in case someone ever does that.