How Python assign multiple variables at one line works?

后端 未结 1 1168
慢半拍i
慢半拍i 2020-11-29 10:48

What are the steps that Python actually does to assign multiple variables at one line?

I use to do A[0], A[1] = A[1], A[0] to swap, but recently I got a bug when ass

相关标签:
1条回答
  • 2020-11-29 11:03

    There's something called "expansion assignment" in Python.

    Long story short, you can expand an iterable with assignment. For example, this code evaluates and expands the right side, which is actually a tuple, and assigns it to the left side:

    a, b = 3, 5
    

    Or

    tup = (3, 5)
    a, b = tup
    

    This means in Python you can exchange two variables with one line:

    a, b = b, a
    

    It evaluates the right side, creates a tuple (b, a), then expands the tuple and assigns to the left side.

    There's a special rule that if any of the left-hand-side variables "overlap", the assignment goes left-to-right.

    i = 0
    l = [1, 3, 5, 7]
    i, l[i] = 2, 0  # l == [1, 3, 0, 7] instead of [0, 3, 5, 7]
    

    So in your code,

    node.next, node.prev = self.next, self
    

    This assignment is parallel, as node.next and node.prev don't "overlap". But for the next line:

    self.next, self.next.prev = node, node
    

    As self.next.prev depends on self.next, they "overlap", thus self.next is assigned first.

    0 讨论(0)
提交回复
热议问题