I have seen many similar questions here, but none of them deal with what I want to know. Let's take an example.
I want to make a linked list from an array. Ignoring all the boilerplate, let's get to the meat of this question.
arr = [1, 2, 3, 4, 5]
tail = head = None # this is the problematic line
for item in arr:
tail = Node(val=item, next=None)
tail = tail.next
return head
Needless to say, this does not work. Head always points to None, no matter what tails points to.
Some other things I have tried:
head = tail = [] # head will point to the empty list after finishing
head = tail = any_other_singleton # does not work
I know why this happens. Its because I am reassigning tail to point to a Node. But I want to keep a reference to the head of the liked list in 'head'. How can I make this work? In other programming languages this is trivial, but in python you have to assign a value to variable when declaring, which is causing me problems.