(Not asking about the solution for this problem, just trying to understand the error)
I get the following error
UnboundLocalError: local variable new_list referenced before assignment
while trying to run this piece of code. My logic was "If new_list
doesn't exist then create new_list
, otherwise use assign new_list.next
, but looks like it doesn't work in this case.
Can someone explain to me why, and what should I do to fix this error?
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
temp = 0
while l1 or l2:
if l1 and l2:
new_val = (l1.val + l2.val) % 10 + temp
new_node = ListNode(new_val)
if l1:
new_node = ListNode(l1.val + temp)
if l2:
new_node = ListNode(l2.val + temp)
if not new_list:
new_list = new_node
else:
new_list.next = new_node
if new_val and new_val > 9:
temp = 1
else:
temp = 0
return new_list