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

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.


Can't tell if this is satire or not. But either way, nice post.


Why would you think it's satire?


How is it different from circular references?


Idk, I guess none, but most languages support this features. Again, maybe this is your first language. But this actually commonly used.
Sorry for that.

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?

Well, it's not commonly used ITSELF, but these is called "circular structures" (I think). A lot of things use this, for example, how DOM elements work:

let parent = {
    "tag": "div",
    "id": "parent"

let child = {
    "tag": "p",
    "id": "child",
    "text": "Child.",
    "parent": parent

// Style 1
parent.child = child;

// Style 2
parent.children = [];

Hopefully this clarifies it for you, if it doesn't, ask me anything you're confused about.

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


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.


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