Add Two Numbers in Python

class Solution:
    def addTwoNumbers(self, l1, l2):
        # Initialize the dummy head of the result list.
        dummy_head = ListNode(0)
        current = dummy_head
        carry = 0

        # Loop through lists l1 and l2 until you reach both ends.
        while l1 or l2:
            # At the start of each iteration, should add carry from last iteration.
            sum = carry
            # Add l1 and l2 values to the sum if they are present.
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next

            # Update carry for next calulation.
            carry = sum // 10
            # Create a new node with the digit value of (sum mod 10) and set it as the next of the current node.
            current.next = ListNode(sum % 10)
            # Move to the next position.
            current = current.next

        # After processing both lists, if there is a carry left, add a new node with carry as the digit.
        if carry > 0:
            current.next = ListNode(carry)

        # The first node is dummy node which we used to simplify code. So return its next node.
        return dummy_head.next

PrevNext