What is this kind of assignment in Python called? a = b = True

前端 未结 4 881
有刺的猬
有刺的猬 2020-11-29 04:20

I know about tuple unpacking but what is this assignment called where you have multiple equals signs on a single line? a la a = b = True

It always trips

4条回答
  •  天命终不由人
    2020-11-29 05:11

    got bitten by python's Chained Assignment today, due to my ignorance. in code

    if l1.val <= l2.val:
        tail = tail.next = l1 # this line 
        l1 = l1.next
    

    what I expected was

    tail.next = l1
    tail = tail.next
    # or equivalently 
    # tail = l1
    

    whereas I got below, which produce a self loop in the list, leave me in a endless loop, whoops...

    tail = l1
    tail.next = l1 # now l1.next is changed to l1 itself
    

    since for a = b = c, one way (python, for example) equivalent to

    tmp = evaluate(c)
    evaluate(a) = tmp
    evaluate(b) = tmp
    

    and have equal right operand for two assignment.

    the other (C++, for example) equivalent to

    evaluate(b) = evaluate(c)
    evaluate(a) = evaluate(b)
    

    since in this case a = b = c is basically

    b = c
    a = b
    

    and two right hand operand could be different.

    That why similar code works well in C++.

提交回复
热议问题