-7

I write a linked list,when I use multiple assignment ,the result is strange。What's the different between python and javascript?

The sample python code

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

node=ListNode(0)
node=node.next=ListNode(10)
#expect node.next=ListNode(10) node=node.next
print(node ==node.next) # True why? 

The same logic JavaScript code

function ListNode(val){
    this.val=val;
    this.next=null;
}
var node=new ListNode(0);
node=node.next=new ListNode(10)
console.log(node==node.next) //false
shenli
  • 13
  • 3

4 Answers4

1

In Python, evaluation is in reverse order. Therefore this:

node = node.next = ListNode(10)

is the same as this:

node = ListNode(10)
node.next = node

So, you have to reverse order of elements before last assignment:

node.next = node = ListNode(10)
# same as:
node.next = ListNode(10)
node = node.next
Thyrst'
  • 2,253
  • 2
  • 22
  • 27
  • The assignment `node.next = node = ListNode(10)` is the equivalent of `tmp = ListNode(10); node.next = tmp; node = tmp`, with the tmp variable hidden. The answer as written suggests that `node` isn't changed by the assignment, which isn't correct. – Craig Apr 09 '17 at 13:37
  • @Craig Thanks. Fixed. :) – Thyrst' Apr 09 '17 at 13:50
  • @Craig where can I know the assignment detail,I can't find in the Python Tutorial – shenli Apr 10 '17 at 02:34
  • @shenli - It's in the [documentation](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) _An assignment statement evaluates the expression list ... and assigns the single resulting object to each of the target lists, **from left to right**_ (emphasis mine). I would avoid using this construction for anything other than simple initialization. You see how much confusion it can cause. H/T: https://stackoverflow.com/questions/14056146/status-of-chained-assignment-in-python – Craig Apr 10 '17 at 02:42
0

Actually you're reassigning node to be equal to node.next, so node == node.next will always be True because those two variables are pointing at the same object.

lch
  • 2,028
  • 2
  • 25
  • 46
0

I'm not sure what you are trying to accomplish with the line:

node = node.next = ListNode(10)

If you just do:

node.next = ListNode(10)

You will get the result you want

in [1]: node=ListNode(0)

In [2]: node.val
Out[2]: 0

In [3]: node.next = ListNode(10)

In [4]: node.val
Out[4]: 0

In [5]: node.next.val
Out[5]: 10

In [6]: node == node.next
Out[6]: False    
Craig
  • 4,605
  • 1
  • 18
  • 28
-1

The assignment operation is evaluated from right to left:

node.next = ListNode(10)
node = node.next
Daniel
  • 42,087
  • 4
  • 55
  • 81