The order of iterable de-referencing in assignment?

Chris Angelico rosuav at gmail.com
Wed Aug 24 07:01:00 EDT 2016


On Wed, Aug 24, 2016 at 8:54 PM, Shiyao Ma <i at introo.me> wrote:
> Given a = [1, 2]
>
> a.extend(a) makes a = [1,2, 1,2]
>
> One might guess a.extend(a) would turn into an infinite loop.  It turns out here Python first gets all the items of `a' and then append them to `a', so the infinite loop is avoided.
>

Be careful: doing the same in Python may not behave that way.

>>> a = [1,2]
>>> for x in a: a.append(x)
...
^CTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>> len(a)
6370805

That right there, folks, is an infinite loop.

ChrisA



More information about the Python-list mailing list