I'm writing a linked list for an educational Python library. Here are the important snippets of code:
class Element(object):
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def insert_back(self, element):
if self.empty():
self.insert_front(element)
else:
self.tail.next = Element(element, None)
self.tail = self.tail.next
# I'd like to replace the above two lines with this
# self.tail = self.tail.next = Element(element, None)
My issue comes from the last line. According to the top answer to this question, Python's unique implementation of chained assignment is the culprit.
In other languages, the last line would have the same effect as the two lines above it, but Python evaluates the expression Element(element, None)
first and then assigns the result from left-to-right, so self.tail
is assigned before self.tail.next
. This results in the previous tail element not referencing the new tail element, and the new tail element referencing itself.
My question is: is there a way to perform these two assignments with a single statement?
I'm perfectly content using the more explicit two-line assignment; this is just for curiosity's sake.