Skip to content

Instantly share code, notes, and snippets.

@cmaspi
Last active May 15, 2022 14:24
Show Gist options
  • Save cmaspi/800f72e225ccdce6a0276dd4d77557ee to your computer and use it in GitHub Desktop.
Save cmaspi/800f72e225ccdce6a0276dd4d77557ee to your computer and use it in GitHub Desktop.
swap in python
a,b = b,a

What does it actually do?
Well, it swaps a and b.. the question is how?

Order of Operations

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the above line of code, two new objects are created which are reference the same object as b, a respectively. Then, we assign them to a,b. The left side will get assigned first, that is a.

We can verify that by

[IN]  a,a = 3,4
[IN]  a
[OUT] 4

Here is a bettern example.

[IN] a = 2
[IN] a, b = 3, a
[IN] a,b
[OUT] (3, 2)

the right hand side is evaluated first, that is 3, a. So even though a is later set to 3, since the rhs was evaluated first, b will be 2

BONUS INFO

Are numbers considered as objects in python?

src

Yes, they are considered objects. All the names are resolved into objects and then on the left side of the assignment, the name references this object.

foo = bar

Here, first bar is resolved into an object, then that object will be referenced by foo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment