1

I'm studying OrderedSet recipe and couldn't understand the following code that implements the doubly linked list.

list_ = []
list_ += [None, list_, list_]
>>> print list_[1]
[None, [...], [...]]
>>> print list_[1][1]
[None, [...], [...]]
>>> print list_[1][1][1]
[None, [...], [...]]
>>> print list_[1][1][1][1]
[None, [...], [...]]
>>> print list_[1][1][1][1][1]
[None, [...], [...]]

How variable assigning to itself in an infinite loop?

1 Answer 1

1

Some variables are not "values", but "pointers".

The list_ variable is a pointer to an existing list.

So, here you're actually creating a list:

pointer_to_list = [] #this list is stored in memory, and the pointer will look at it

Here, you add three elements to the list:

pointer_to_list += [None, pointer_to_list, pointer_to_list]

This list contains 3 elements. None, pointer, pointer.

But it happens that the pointer points to the list itself. This doesn't mean that it's being infinitely "assigned", just that if you get the value of the pointer, you're getting the whole list.

And the list contains the pointer. And the pointer points to the list, and the list contains the pointer, and the pointer points to the list.....

This results in you being able to infinitely get the list inside the list inside the list.

But in truth, only one list exists, containing three elements: None, pointer, pointer.


This could be done also with list_ += [None, list_]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.