The implementation mechanism of variable exchange x,y=y,x--tuple

Source: Internet
Author: User

There is an assignment mechanism in Python that assigns values in this way, and the objects on both sides of the equal sign are tuples and the parentheses of the tuples are optional. The usual form is

' A String '

Equal to (x, y, Z) = (1, 2, 'a string')

The most frequently used environment for this type of assignment is variable exchange, which is shaped like

X, y = y, X

This exchange method does not require an intermediate variable to exchange the values of two variables. So what is the concrete implementation mechanism?

At run time, first constructs a tuple (y, x), then constructs another tuple (x, y), then assigns (x, y) with tuples (y, x), and the tuple assignment process is left to right and sequentially. If x=1,y=2, shilling x=y, at this time x=2, then make y=x,y should be equal to 2? So the variable exchange is not possible? For this problem, you should start with the characteristics of the tuple.

' A String '  = (x, y, z)

Variable names x, Y, Z are references, memory opens up except three spaces that store 1, 2, ' A string ', three variables pointing to the three-block address respectively. The tuple, constructed of these three variables, has three elements, three of which are not the three variables of x, Y, Z, but the contents of the address space to which the three variables point. If at this point another x=4, at this time in the address space will open up another space storage 4,x and then point to this space, and the tuple of three values remain unchanged.

So for x, y = y, x , the tuple (y,x), first composed by y,x, should be represented as (2,1), then the value of the variable can be exchanged from left to right.

The implementation mechanism of variable exchange x,y=y,x--tuple

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.