Sunday, 1 December 2019

Is there any usage of self-referential lists or circular reference in list, eg. appending a list to itself

So if I have a list a and append a to it, I will get a list that contains it own reference.

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

And this basically results in seemingly infinite recursions.

And not only in lists, dictionaries as well:

>>> b = {'a':1,'b':2}
>>> b['c'] = b
>>> b
{'a': 1, 'b': 2, 'c': {...}}

It could have been a good way to store the list in last element and modify other elements, but that wouldn't work as the change will be seen in every recursive reference.

I get why this happens, i.e. due to their mutability. However, I am interested in actual use-cases of this behavior. Can somebody enlighten me?



from Is there any usage of self-referential lists or circular reference in list, eg. appending a list to itself

No comments:

Post a Comment