Achal
Achal

Reputation: 11921

Self referential list in python?

While analyzing python list I got surprised when I saw something which is not possible in other programming language. Lets say I have a list called my_list

my_list = [1,2,3,4,5,6,7,8,9,10] 

Next when I'm doing like

my_list[9] = my_list  #I didn't seen such things possible in C/C++

And when I'm printing my_list, my_list[9] and my_list[9][9], all these gives the same results.

my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
my_list[9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
my_list[9][9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]

What I understood is that my_list[9] is referring to same list called my_list and [...] means self referential list i.e list pointing to same list as when you do type(my_list[9]) it gives me type as list.

[1, 2, 3, 4, 5, 6, 7, 8, 9, [...]]
                              |
             Does it like self referential struct pointer concept of C ?

Above my_list example I just added for simple test run. I want to know how things like my_list[9] = my_list makes python code performance better. what is the actual intention behind this my_list[9] = my_list making possible in python ?

Any help will be greatly appreciated.

Upvotes: 2

Views: 991

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

It's possible because a list (like other containers) store references, and why not a reference of itself?

The __str__ / __repr__ functions have been protected against this to avoid infinite recursion, and show an ellipsis instead (...).

Why is it possible? Because it's not impossible. If Python were to prevent that, it would mean checking for self-referencing every time an object is added in the list. This would either be an additional O(n) storage overhead for maintaining a reference cache, or an O(n) time overhead for performing a reference search.

Upvotes: 3

nosklo
nosklo

Reputation: 222862

Lists in python don't contain anything except references to objects (like a pointer). They can refer to any object including themselves.

Upvotes: 2

Related Questions