Self-containing lists...?!?

yujiri8 profile image Ryan Westlund ・1 min read

So today I was reading the Python Design and History FAQ and I learned about a really weird feature: Lists can contain themselves!

>>> a = [1, 2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>> a[2][2][2]
[1, 2, [...]]
>>> a[2][2][2][0]
>>> a[0] = a
>>> a
[[...], 2, [...]]
>>> a = [a,a,a]
>>> a
[[[...], 2, [...]], [[...], 2, [...]], [[...], 2, [...]]]

Well... mind blown...


markdown guide

Lol, it kind of is my first language - or was. But I've known it for almost 7 years and know at least 5 other general-purpose languages (Go, Javascript, Haskell, Rust, C).

How is this "commonly" used?


This is something I sort of knew but haven't given much thought. I wonder if the element access is constrained by the max recursion-depth? Btw, this is the reason python has a garbage collector. Reference counting breakers down with circular dependencies like this.


Now print our the contents of a


It has same result as returning a in python console. Including for-loop. Flattening doesn't help too.


Why would you think it's satire?


How is it different from circular references?

Hmm I guess I just never rthought of it as an extension of objects pointing to each other


It is just contain reference to itself.
It is called circular list.