DEV Community

loading...

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]
1
>>> a[0] = a
>>> a
[[...], 2, [...]]
>>> a = [a,a,a]
>>> a
[[[...], 2, [...]], [[...], 2, [...]], [[...], 2, [...]]]
Enter fullscreen mode Exit fullscreen mode

Well... mind blown...

Discussion

pic
Editor guide
yujiri8 profile image
Ryan Westlund Author

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?

Collapse
fronkan profile image
Fredrik Bengtsson

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.

Collapse
Collapse
delta456 profile image
Collapse
shane profile image
shane

Now print our the contents of a

Collapse
pontakornth profile image
pontakornth

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

Collapse
yujiri8 profile image
Ryan Westlund Author

Why would you think it's satire?

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

How is it different from circular references?

yujiri8 profile image
Ryan Westlund Author

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

Collapse
gkucmierz profile image
Grzegorz Kućmierz

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