# Clear python code, straight forward

• ``````class Solution:
# @return a ListNode
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
n.next = ListNode(val)
n = n.next
return root.next``````

• You can write second last 2 lines in only one:

n.next = n = ListNode(val)

• Yes, quite right, BTW, from checkio?

• But this consecutive assignments is a little unclear for me, perhaps tuple assignment is better?

• Shouldn't it be: n = n.next = ListNode(val)?Why?

• This post is deleted!

• I found this Stack Overflow to find out the answer.

n.next = n = ListNode(val) means first n.next = ListNode(val) then n point to the same address

n = n.next = ListNode(val) means first n = ListNode(val) , now the n is ListNode(val), then n.next point to the address ListNode(val) which means point to itself!!!

Hope this will help.

• nice solution! However, I think the variable v1, v2 is unnecessary.

`````` def addTwoNumbers(self, l1, l2):
carry = 0;
res = n = ListNode(0);
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next;
if l2:
carry += l2.val;
l2 = l2.next;
carry, val = divmod(carry, 10)
n.next = n = ListNode(val);
return res.next;``````

• may i ask what does if l1: if l2: mean here? sry I'm new to python

• n.next = n = ListNode(val) 与 n = n.next = ListNode(val)
is there any different?thanks

• that's really help me :)

• Almost the same idea as my. But I don't make good use of these functions already included in Python. I make it by myself.

• may be slow when adding one small number with a large number like 1 plus 100000000, I use the way that appending the rest of link list to the final result when one of the list is None and the carry is 0

• @tusizi I didn't go on this site for a long time, yes from CheckiO, you too?

• @mxmingya It just checks if the current node is None

• @mxmingya l1 = list 1
l2 = list 2

• Amazing. Learning a lot about python from just reading this solution

• Please can some one tell me what is this ListNode class I don't find it online though

• @jysun The class is given in the question.

• @jysun

class ListNode(object):
def init(self, x):
self.val = x
self.next = None

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.